cases.gno
2.28 Kb · 97 lines
1package gauntlet
2
3import (
4 "errors"
5 "strings"
6)
7
8// Case is one fixed test: Solve(In) must return exactly Want.
9type Case struct {
10 In string
11 Want string
12}
13
14// Solver is the function a solution exposes.
15type Solver func(in string) string
16
17// Judge lets a poster define correctness with code instead of fixed answers.
18// Inputs returns fresh inputs for a seed; Check reports whether out is a
19// correct answer for in. Checking is usually far cheaper than solving.
20type Judge struct {
21 Inputs func(seed uint64) []string
22 Check func(in, out string) bool
23}
24
25const (
26 MaxCases = 64
27 MaxFieldLen = 2048
28)
29
30var (
31 ErrNoCases = errors.New("gauntlet: no test cases")
32 ErrTooManyCase = errors.New("gauntlet: too many test cases")
33 ErrBadCaseLine = errors.New("gauntlet: each case line must be `input => want`")
34 ErrFieldTooBig = errors.New("gauntlet: test case too large")
35)
36
37// ParseCases reads one case per line in the form `input => want`.
38// Inside a field, `\n` is a newline, `\t` a tab and `\\` a backslash.
39// Blank lines and lines starting with `#` are ignored.
40func ParseCases(src string) ([]Case, error) {
41 var out []Case
42 for _, line := range strings.Split(src, "\n") {
43 line = strings.TrimRight(line, "\r")
44 if strings.TrimSpace(line) == "" || strings.HasPrefix(strings.TrimSpace(line), "#") {
45 continue
46 }
47 idx := strings.Index(line, " => ")
48 if idx < 0 {
49 return nil, ErrBadCaseLine
50 }
51 c := Case{In: Unescape(line[:idx]), Want: Unescape(line[idx+4:])}
52 if len(c.In) > MaxFieldLen || len(c.Want) > MaxFieldLen {
53 return nil, ErrFieldTooBig
54 }
55 out = append(out, c)
56 if len(out) > MaxCases {
57 return nil, ErrTooManyCase
58 }
59 }
60 if len(out) == 0 {
61 return nil, ErrNoCases
62 }
63 return out, nil
64}
65
66// Escape makes a value safe to place on one case line.
67func Escape(s string) string {
68 s = strings.ReplaceAll(s, `\`, `\\`)
69 s = strings.ReplaceAll(s, "\n", `\n`)
70 s = strings.ReplaceAll(s, "\t", `\t`)
71 return s
72}
73
74// Unescape reverses Escape.
75func Unescape(s string) string {
76 var b strings.Builder
77 for i := 0; i < len(s); i++ {
78 if s[i] == '\\' && i+1 < len(s) {
79 switch s[i+1] {
80 case 'n':
81 b.WriteByte('\n')
82 i++
83 continue
84 case 't':
85 b.WriteByte('\t')
86 i++
87 continue
88 case '\\':
89 b.WriteByte('\\')
90 i++
91 continue
92 }
93 }
94 b.WriteByte(s[i])
95 }
96 return b.String()
97}