-
Notifications
You must be signed in to change notification settings - Fork 0
/
randhex.go
55 lines (43 loc) · 1.29 KB
/
randhex.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
package randhex
import (
"crypto/rand"
"encoding/hex"
"errors"
"strings"
)
// RandHex is a container for a random hexadecimal color code
type RandHex struct {
bytes []byte
}
// New generates a new random hexadecimal color code
func New() RandHex {
bytes := make([]byte, 3)
rand.Read(bytes)
return RandHex{bytes: bytes}
}
// String provides the hexadecimal color code in string format
func (randhex RandHex) String() string {
return strings.ToUpper("#" + hex.EncodeToString(randhex.bytes))
}
// Bytes provides the bytes of the hexadecimal color code
func (randhex RandHex) Bytes() []byte {
val := make([]byte, 3)
copy(val, randhex.bytes)
return val
}
// ParseString parses a string representation of a hexcode into a RandHex
func ParseString(str string) (randhex RandHex, err error) {
noHash := strings.Replace(str, "#", "", -1)
noHash = strings.ToLower(noHash)
if len(noHash) == 3 {
noHash = string(noHash[0]) + string(noHash[0]) + string(noHash[1]) + string(noHash[1]) + string(noHash[2]) + string(noHash[2])
}
if len(noHash) != 6 {
return RandHex{}, errors.New(str + " is not a valid hexadecimal color code. Hexadecimal color codes must be 3 or 6 digits.")
}
bytes, err := hex.DecodeString(noHash)
if err != nil {
return RandHex{}, err
}
return RandHex{bytes: bytes}, nil
}