-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
64 lines (52 loc) · 1.07 KB
/
example_test.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
package parser_test
import (
"fmt"
"os"
"strconv"
"github.com/FollowTheProcess/parser"
)
// RGB represents a colour.
type RGB struct {
Red int
Green int
Blue int
}
// fromHex parses a string into a hex digit.
func fromHex(s string) (int, error) {
hx, err := strconv.ParseInt(s, 16, 64)
return int(hx), err
}
// hexPair is a parser that converts a hex string into it's integer value.
func hexPair(colour string) (int, string, error) {
return parser.Map(
parser.Take(2),
fromHex,
)(colour)
}
func Example() {
// Let's parse this into an RGB
colour := "#2F14DF"
// We don't actually care about the #
_, colour, err := parser.Char('#')(colour)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
// We want 3 hex pairs
pairs, _, err := parser.Count(hexPair, 3)(colour)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
if len(pairs) != 3 {
fmt.Fprintln(os.Stderr, err)
return
}
rgb := RGB{
Red: pairs[0],
Green: pairs[1],
Blue: pairs[2],
}
fmt.Printf("%#v\n", rgb)
// Output: parser_test.RGB{Red:47, Green:20, Blue:223}
}