~mendelmaleh/dummy

ref: b862a107cb4810e7514eccf69deb3fc5f6f5dc4c dummy/utils.go -rw-r--r-- 1.1 KiB
b862a107Mendel E Document new endpoints 1 year, 4 months ago
                                                                                
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
package dummy

import (
	"errors"
	"fmt"
	"image/color"
)

// Hex to color.RGBA conversion. Accepts an optional '#', then one of the following formats:
// RGB RGBA RRGGBB RRGGBBAA
func Hex(s string) (c color.RGBA, err error) {
	if len(s) < 1 {
		return c, errors.New("can't convert empty string")
	}

	if s[0] == '#' {
		s = s[1:]
	}

	htb := func(b byte) byte {
		switch {
		case '0' <= b && b <= '9':
			return b - '0'
		case 'a' <= b && b <= 'z':
			return b - 'a' + 10
		case 'A' <= b && b <= 'Z':
			return b - 'A' + 10
		}
		err = fmt.Errorf("htb: invalid byte %d\n", b)
		return 0
	}

	c.A = ^uint8(0)
	l := len(s)

	switch {
	case l < 3:
		return color.RGBA{}, errors.New("string needs to have minimum len of 3")
	case l <= 4:
		c.R = htb(s[0]) * 17
		c.G = htb(s[1]) * 17
		c.B = htb(s[2]) * 17

		if l == 4 {
			c.A = htb(s[3]) * 17
		}
	case l == 6 || l == 8:
		c.R = htb(s[0])<<4 + htb(s[1])
		c.G = htb(s[2])<<4 + htb(s[3])
		c.B = htb(s[4])<<4 + htb(s[5])

		if l == 8 {
			c.A = htb(s[6])<<4 + htb(s[7])
		}
	default:
		return color.RGBA{}, fmt.Errorf("invalid length string %q", s)
	}

	return c, err
}