-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkey.go
More file actions
43 lines (36 loc) · 1.07 KB
/
Copy pathkey.go
File metadata and controls
43 lines (36 loc) · 1.07 KB
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
package lease
import (
"fmt"
"strings"
"unicode/utf8"
)
// MaxKeyBytes bounds a complete encoded lease key.
const MaxKeyBytes = 256
// Key is a validated, namespaced lease identity.
type Key struct {
value string
}
// NewKey constructs a bounded key from non-empty namespace and name segments.
func NewKey(namespace, name string) (Key, error) {
value := namespace + "/" + name
if !validSegment(namespace) || !validSegment(name) || len(value) > MaxKeyBytes {
return Key{}, fmt.Errorf("%w: invalid key", ErrInvalidState)
}
return Key{value: value}, nil
}
// ParseKey validates a canonical namespace/name representation.
func ParseKey(value string) (Key, error) {
namespace, name, found := strings.Cut(value, "/")
if !found {
return Key{}, fmt.Errorf("%w: invalid key", ErrInvalidState)
}
return NewKey(namespace, name)
}
// String returns the canonical namespaced representation.
func (key Key) String() string {
return key.value
}
func validSegment(segment string) bool {
return segment != "" && utf8.ValidString(segment) &&
!strings.ContainsAny(segment, "\x00\r\n")
}