This repository has been archived by the owner on Oct 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
key.go
70 lines (55 loc) · 1.74 KB
/
key.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
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"bytes"
"encoding/binary"
"errors"
"regexp"
)
var ExtractKeyParseError = errors.New("ExtractKey: parse error, possibly because seprator was not found")
// Marshal keys
func validObj(obj string) bool {
return obj == "bite" || obj == "user"
}
// TODO: ensure security of regexp
var validConversationRegexp = regexp.MustCompile(`^[a-zA-Z0-9-]+$`)
func validConversation(conversation string) bool {
return validConversationRegexp.MatchString(conversation)
}
const conversationSeprator = '@'
const objSeprator = '+'
func MarshalKey(obj, conversation string, start uint64) ([]byte, error) {
prefixBytes, err := MarshalKeyPrefix(obj, conversation)
if err != nil {
return nil, err
}
startBytes := make([]byte, 8)
binary.BigEndian.PutUint64(startBytes, start)
return append(prefixBytes, startBytes...), nil
}
func MarshalKeyPrefix(obj, conversation string) ([]byte, error) {
if !validObj(obj) || !validConversation(conversation) {
return nil, errors.New("main: FormatKey: bad obj or conversation")
}
return []byte(obj + string(objSeprator) + conversation + string(conversationSeprator)), nil
}
func ExtractKey(b []byte) (string, string, uint64, error) {
startStart := bytes.LastIndexByte(b, conversationSeprator) + 1
if startStart < 0 {
return "", "", 0, ExtractKeyParseError
}
startBytes := b[startStart:]
convStart := bytes.LastIndexByte(b[:startStart-1], objSeprator) + 1
if convStart < 0 {
return "", "", 0, ExtractKeyParseError
}
convBytes := b[convStart : startStart-1]
objStart := 0
if objStart < 0 {
return "", "", 0, ExtractKeyParseError
}
objBytes := b[objStart : convStart-1]
obj := string(objBytes)
conv := string(convBytes)
start := binary.BigEndian.Uint64(startBytes)
return obj, conv, start, nil
}