summaryrefslogtreecommitdiff
path: root/pkg/util/fmt_test.go
blob: d2579d05467f7e3cf3cce34e41c2eac773682f98 (plain)
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
89
90
91
92
93
94
95
96
97
98
99
package util_test

import (
	"fmt"
	"testing"

	"github.com/stretchr/testify/assert"

	"lukeshu.com/btrfs-tools/pkg/util"
)

type FmtState struct {
	MWidth     int
	MPrec      int
	MFlagMinus bool
	MFlagPlus  bool
	MFlagSharp bool
	MFlagSpace bool
	MFlagZero  bool
}

func (st FmtState) Width() (int, bool) {
	if st.MWidth < 1 {
		return 0, false
	}
	return st.MWidth, true
}

func (st FmtState) Precision() (int, bool) {
	if st.MPrec < 1 {
		return 0, false
	}
	return st.MPrec, true
}

func (st FmtState) Flag(b int) bool {
	switch b {
	case '-':
		return st.MFlagMinus
	case '+':
		return st.MFlagPlus
	case '#':
		return st.MFlagSharp
	case ' ':
		return st.MFlagSpace
	case '0':
		return st.MFlagZero
	}
	return false
}

func (st FmtState) Write([]byte) (int, error) {
	panic("not implemented")
}

func (dst *FmtState) Format(src fmt.State, verb rune) {
	if width, ok := src.Width(); ok {
		dst.MWidth = width
	}
	if prec, ok := src.Precision(); ok {
		dst.MPrec = prec
	}
	dst.MFlagMinus = src.Flag('-')
	dst.MFlagPlus = src.Flag('+')
	dst.MFlagSharp = src.Flag('#')
	dst.MFlagSpace = src.Flag(' ')
	dst.MFlagZero = src.Flag('0')
}

// letters only? No 'p', 'T', or 'w'.
const verbs = "abcdefghijklmnoqrstuvxyzABCDEFGHIJKLMNOPQRSUVWXYZ"

func FuzzFmtStateString(f *testing.F) {
	f.Fuzz(func(t *testing.T,
		width, prec uint8,
		flagMinus, flagPlus, flagSharp, flagSpace, flagZero bool,
		verbIdx uint8,
	) {
		if flagMinus {
			flagZero = false
		}
		input := FmtState{
			MWidth:     int(width),
			MPrec:      int(prec),
			MFlagMinus: flagMinus,
			MFlagPlus:  flagPlus,
			MFlagSharp: flagSharp,
			MFlagSpace: flagSpace,
			MFlagZero:  flagZero,
		}
		verb := rune(verbs[int(verbIdx)%len(verbs)])

		t.Logf("(%#v, %c) => %q", input, verb, util.FmtStateString(input, verb))

		var output FmtState
		assert.Equal(t, "", fmt.Sprintf(util.FmtStateString(input, verb), &output))
		assert.Equal(t, input, output)
	})
}