aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/kr/logfmt/scanner.go
blob: 095221ff24bf4cdb6876a2906bfce4c4b0f07ce9 (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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
package logfmt

import (
	"errors"
	"fmt"
)

var ErrUnterminatedString = errors.New("logfmt: unterminated string")

func gotoScanner(data []byte, h Handler) (err error) {
	saveError := func(e error) {
		if err == nil {
			err = e
		}
	}

	var c byte
	var i int
	var m int
	var key []byte
	var val []byte
	var ok bool
	var esc bool

garbage:
	if i == len(data) {
		return
	}

	c = data[i]
	switch {
	case c > ' ' && c != '"' && c != '=':
		key, val = nil, nil
		m = i
		i++
		goto key
	default:
		i++
		goto garbage
	}

key:
	if i >= len(data) {
		if m >= 0 {
			key = data[m:i]
			saveError(h.HandleLogfmt(key, nil))
		}
		return
	}

	c = data[i]
	switch {
	case c > ' ' && c != '"' && c != '=':
		i++
		goto key
	case c == '=':
		key = data[m:i]
		i++
		goto equal
	default:
		key = data[m:i]
		i++
		saveError(h.HandleLogfmt(key, nil))
		goto garbage
	}

equal:
	if i >= len(data) {
		if m >= 0 {
			i--
			key = data[m:i]
			saveError(h.HandleLogfmt(key, nil))
		}
		return
	}

	c = data[i]
	switch {
	case c > ' ' && c != '"' && c != '=':
		m = i
		i++
		goto ivalue
	case c == '"':
		m = i
		i++
		esc = false
		goto qvalue
	default:
		if key != nil {
			saveError(h.HandleLogfmt(key, val))
		}
		i++
		goto garbage
	}

ivalue:
	if i >= len(data) {
		if m >= 0 {
			val = data[m:i]
			saveError(h.HandleLogfmt(key, val))
		}
		return
	}

	c = data[i]
	switch {
	case c > ' ' && c != '"' && c != '=':
		i++
		goto ivalue
	default:
		val = data[m:i]
		saveError(h.HandleLogfmt(key, val))
		i++
		goto garbage
	}

qvalue:
	if i >= len(data) {
		if m >= 0 {
			saveError(ErrUnterminatedString)
		}
		return
	}

	c = data[i]
	switch c {
	case '\\':
		i += 2
		esc = true
		goto qvalue
	case '"':
		i++
		val = data[m:i]
		if esc {
			val, ok = unquoteBytes(val)
			if !ok {
				saveError(fmt.Errorf("logfmt: error unquoting bytes %q", string(val)))
				goto garbage
			}
		} else {
			val = val[1 : len(val)-1]
		}
		saveError(h.HandleLogfmt(key, val))
		goto garbage
	default:
		i++
		goto qvalue
	}
}
nihil fit ex nihilo