-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathname.go
58 lines (50 loc) · 1.65 KB
/
name.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package grid
import (
"fmt"
"regexp"
"sync"
)
const validActorName = "^[a-zA-Z0-9-_]+$"
var (
validActorNameRegEx *regexp.Regexp = regexp.MustCompile(validActorName)
knownNamespaces sync.Map
)
// isNameValid returns true if the name matches the
// regular expression "^[a-zA-Z0-9-_]+$".
func isNameValid(name string) bool {
if name == "" {
return false
}
return validActorNameRegEx.MatchString(name)
}
func stripNamespace(t EntityType, namespace, fullname string) (string, error) {
plen := len(namespace) + 1 + len(t) + 1
if len(fullname) <= plen {
return "", fmt.Errorf("%w: namespace=%s fullname=%s plen=%d", ErrInvalidName, namespace, fullname, plen)
}
return fullname[plen:], nil
}
func namespaceName(t EntityType, namespace, name string) (string, error) {
if !isNameValid(name) {
return "", fmt.Errorf("%w: namespace=%s name=%s", ErrInvalidName, namespace, name)
}
// an optimization to reduce memory allocations is to
// check if we've seen this namespace before. To avoid allocating
// a regEx on each request.
if _, seen := knownNamespaces.Load(namespace); !seen {
if !isNameValid(namespace) {
return "", fmt.Errorf("%w: namespace=%s name=%s", ErrInvalidNamespace, namespace, name)
}
knownNamespaces.Store(namespace, struct{}{})
}
return fmt.Sprintf("%v.%v.%v", namespace, t, name), nil
}
func namespacePrefix(t EntityType, namespace string) (string, error) {
if _, seen := knownNamespaces.Load(namespace); !seen {
if !isNameValid(namespace) {
return "", fmt.Errorf("%w: namespace=%s", ErrInvalidNamespace, namespace)
}
knownNamespaces.Store(namespace, struct{}{})
}
return fmt.Sprintf("%v.%v.", namespace, t), nil
}