-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.go
88 lines (75 loc) · 2.03 KB
/
utils.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* PAKT - Interlink Remote Applications
* Copyright (C) 2016 Roland Singer <roland.singer[at]desertbit.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package pakt
import (
"crypto/rand"
"encoding/binary"
"errors"
"github.com/sirupsen/logrus"
)
const (
uint32Max = 4294967295
uint16Max = 65535
)
var (
// Log is the public logrus value used internally.
Log *logrus.Logger
endian binary.ByteOrder = binary.BigEndian
errInvalidByteLen = errors.New("invalid byte length")
)
func init() {
// Create a new logger instance.
Log = logrus.New()
}
func bytesToUint16(data []byte) (v uint16, err error) {
if len(data) < 2 {
return 0, errInvalidByteLen
}
v = endian.Uint16(data)
return
}
func uint16ToBytes(v uint16) (data []byte, err error) {
data = make([]byte, 2)
endian.PutUint16(data, v)
return
}
func bytesToUint32(data []byte) (v uint32, err error) {
if len(data) < 4 {
return 0, errInvalidByteLen
}
v = endian.Uint32(data)
return
}
func uint32ToBytes(v uint32) (data []byte, err error) {
data = make([]byte, 4)
endian.PutUint32(data, v)
return
}
// randomString generates a random string.
func randomString(n int) (string, error) {
const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
var bytes = make([]byte, n)
_, err := rand.Read(bytes)
if err != nil {
return "", err
}
for i, b := range bytes {
bytes[i] = alphanum[b%byte(len(alphanum))]
}
return string(bytes), nil
}