@@ -13,17 +13,22 @@ import (
13
13
14
14
type Identifier string
15
15
16
+ const (
17
+ maximumLongLength = 50
18
+ shortLength = 16
19
+ )
20
+
16
21
func (i Identifier ) Long () string {
17
22
re := regexp .MustCompile (`(?s)^tpi-([a-z0-9]+(?:[a-z0-9-]*[a-z0-9])?)-([a-z0-9]+)-([a-z0-9]+)$` )
18
23
19
- if match := re .FindStringSubmatch (string (i )); len (match ) > 0 && hash (match [1 ]+ match [2 ], 4 ) == match [3 ] {
24
+ if match := re .FindStringSubmatch (string (i )); len (match ) > 0 && hash (match [1 ]+ match [2 ], shortLength / 2 ) == match [3 ] {
20
25
return match [0 ]
21
26
}
22
27
23
- name := normalize (string (i ), 50 )
24
- digest := hash (string (i ), 4 )
28
+ name := normalize (string (i ), maximumLongLength - shortLength - uint32 ( len ( "tpi---" )) )
29
+ digest := hash (string (i ), shortLength / 2 )
25
30
26
- return fmt .Sprintf ("tpi-%s-%s-%s" , name , digest , hash (name + digest , 4 ))
31
+ return fmt .Sprintf ("tpi-%s-%s-%s" , name , digest , hash (name + digest , shortLength / 2 ))
27
32
}
28
33
29
34
func (i Identifier ) Short () string {
@@ -33,13 +38,18 @@ func (i Identifier) Short() string {
33
38
34
39
// hash deterministically generates a Base36 digest of `size`
35
40
// characters using `identifier` as the seed.
36
- func hash (identifier string , size uint32 ) string {
41
+ func hash (identifier string , size uint8 ) string {
37
42
digest := sha256 .Sum256 ([]byte (identifier ))
38
43
random := uid .NewRandCustom (bytes .NewReader (digest [:]))
39
44
encoder := uid .NewEncoderBase36 ()
40
- provider := uid .NewProviderCustom (size , random , encoder )
45
+ provider := uid .NewProviderCustom (sha256 .Size , random , encoder )
46
+ result := provider .MustGenerate ().String ()
41
47
42
- return provider .MustGenerate ().String ()
48
+ if len (result ) < int (size ) {
49
+ panic ("not enough bytes to satisfy requested size" )
50
+ }
51
+
52
+ return result [:size ]
43
53
}
44
54
45
55
// normalize normalizes user-provided identifiers by adapting them to
@@ -48,13 +58,10 @@ func normalize(identifier string, truncate uint32) string {
48
58
lowercase := strings .ToLower (identifier )
49
59
50
60
normalized := regexp .MustCompile ("[^a-z0-9]+" ).ReplaceAllString (lowercase , "-" )
51
- normalized = regexp .MustCompile ("(^-)|(-$)" ).ReplaceAllString (normalized , "" )
52
61
53
62
if len (normalized ) > int (truncate ) {
54
63
normalized = normalized [:truncate ]
55
64
}
56
65
57
- return normalized
66
+ return regexp . MustCompile ( "(^-)|(-$)" ). ReplaceAllString ( normalized , "" )
58
67
}
59
-
60
- // func NormalizeIdentifier(identifier common.Identifier, long bool) string {
0 commit comments