github.com/qioalice/ekago/v3@v3.3.2-0.20221202205325-5c262d586ee4/ekaerr/namespace_id.go (about) 1 // Copyright © 2020. All rights reserved. 2 // Author: Ilya Stroy. 3 // Contacts: iyuryevich@pm.me, https://github.com/qioalice 4 // License: https://opensource.org/licenses/MIT 5 6 package ekaerr 7 8 import ( 9 "sync/atomic" 10 ) 11 12 type ( 13 // NamespaceID is just int32 alias and has been introduced to make it easy 14 // to replace underlying type to something other in the future. 15 NamespaceID = int32 16 ) 17 18 //noinspection GoSnakeCaseUsage 19 const ( 20 // _ERR_INVALID_NAMESPACE_ID is a special reserved invalid Namespace ID 21 // that is used to mark that some Namespace is invalid. 22 _ERR_INVALID_NAMESPACE_ID = -1 23 ) 24 25 var ( 26 // namespaceIDPrivateCounter is an internal ClassID counter that is increased 27 // at the new error Namespace creating. 28 // 29 // DO NOT USE IT DIRECTLY! Use newNamespaceID() instead. 30 namespacePrivateCounterID ClassID 31 ) 32 33 // newNamespaceID returns new NamespaceID value that can be used as new Namespace's ID. 34 // Thread-safety. 35 func newNamespaceID() NamespaceID { 36 return atomic.AddInt32(&namespacePrivateCounterID, 1) 37 } 38 39 // isValidNamespaceID reports whether 'namespaceID' is valid Namespace's ID. 40 // Remember, it has been done to avoid cases when Namespace object has been manually 41 // instantiated (like 'new(Namespace)' or 'var _ Namespace') and thus has not been initialized. 42 func isValidNamespaceID(namespaceID NamespaceID) bool { 43 // Because in the Namespace object ID is private and can not be accessed 44 // from the outside, it's enough to check whether it's not 0 (manually instantiated), 45 // but theoretically classID may be equal _ERR_INVALID_NAMESPACE_ID. Check it too. 46 return namespaceID > 0 && namespaceID != _ERR_INVALID_NAMESPACE_ID 47 } 48 49 // namespaceByID returns Namespace object bases on 'namespaceID'. 50 // WARNING! Make sure you checked whether provided 'namespaceID' is valid using 51 // isValidNamespaceID() func. UB otherwise (may panic). 52 func namespaceByID(namespaceID NamespaceID, lock bool) Namespace { 53 if namespaceID < _ERR_NAMESPACE_ARRAY_CACHE { 54 return registeredNamespacesArr[namespaceID] 55 } else { 56 if lock { 57 registeredNamespacesMap.RLock() 58 defer registeredNamespacesMap.RUnlock() 59 } 60 return registeredNamespacesMap.m[namespaceID] 61 } 62 }