~mna/zerojson

ref: 9815e26416ae791fd399d7f857f99c0e9cb22a3f zerojson/zerojson.go -rw-r--r-- 4.9 KiB
9815e264Martin Angers peek, scan literal 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
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package zerojson

import (
	"fmt"
	"io"
)

// errorString allows a string constant to be an error.
type errorString string

func (e errorString) Error() string {
	return string(e)
}

const (
	// ErrIncompleteLiteral is the error representing an incomplete true, false or
	// null literal.
	ErrIncompleteLiteral errorString = "incomplete literal"
)

// JSON supports 7 different values:
//
// - Object, starting with '{'
// - Array, starting with '['
// - String, starting with '"'
// - Number, starting with '-' or [0-9]
// - True, starting with 't'
// - False, starting with 'f'
// - Null, starting with 'n'
//
// Of those, Object and Array can nest and as such require a stack.
// However, since String and Number can be arbitrarily long, when tokenizing
// with a limited buffer, those values may be broken down in multiple chunks
// too.
//
// Also, when processing an Object, the parser must keep track of whether
// it is processing a key or a value (both may be strings).

const (
	staticStackSize = 4

	trueTrail  = "rue"
	falseTrail = "alse"
	nullTrail  = "ull"

	// Code point 00 (NUL) is invalid in JSON, use it as eof marker
	eof = '\x00'
)

type stack struct {
	depth int
	cur   byte

	// each uint64 can store 64 levels deep (1 bit is sufficient per level)
	static [staticStackSize]uint64
	// for very deeply-nested JSON, resort to allocation
	dynamic []uint64
}

// It is expected that v is either '{' or '['. Behaviour is undefined
// if a different value is provided.
func (s *stack) push(v byte) {
	// depth 0 means nothing pushed on the stack, so to find the bit
	// index we need to get depth *before* incrementing it, and then
	// module 64 as each uint64 has 64 bits.
	wordIndex := s.depth / 64
	bitIndex := s.depth % 64
	s.depth++
	s.cur = v

	// set bit to 1 for Object, 0 for Array, by dividing the byte
	// by '{'. That is:
	// '{' / '{' == 1 ==> Object
	// '[' / '{' == 0 ==> Array
	bit := uint64(v / '{')

	if wordIndex < staticStackSize {
		s.static[wordIndex] |= bit << uint(bitIndex)
		return
	}

	wordIndex -= staticStackSize
	if wordIndex >= len(s.dynamic) {
		s.dynamic = append(s.dynamic, 0)
	}
	s.dynamic[wordIndex] |= bit << uint(bitIndex)
}

func (s *stack) peek() byte {
	if s.cur > 0 || s.depth == 0 {
		return s.cur
	}

	ix := s.depth - 1
	wordIndex := ix / 64
	bitIndex := ix % 64

	var word uint64
	if wordIndex < staticStackSize {
		word = s.static[wordIndex]
	} else {
		wordIndex -= staticStackSize
		word = s.dynamic[wordIndex]
	}
	if word&(1<<uint(bitIndex)) == 0 {
		s.cur = '['
	} else {
		s.cur = '{'
	}
	return s.cur
}

func (s *stack) pop() byte {
	b := s.peek()
	s.depth--
	s.cur = 0 // unset, will need to be read on peek
	return b
}

type parser struct {
	// immutable fields
	// input is the data to parse
	input []byte
	// emit is called for each parsed tokens with the type of token, the
	// value and an error if the token is an invalid token. If the function returns
	// an error, the parsing stops, otherwise it continues with the next
	// token.
	//
	// The type may be:
	// '{' : start of an object (v is '{')
	// '[' : start of an array (v is '[')
	// '"' : a string (v is the full string, with quotes)
	// '1' : a number (v is the full number)
	// 't' : true (v is the full literal)
	// 'f' : false (v is the full literal)
	// 'n' : null (v is the full literal)
	// '\x00' : unknown or eof, only provided with a non-nil err
	//
	// The value v is a slice into the original input, it should not be
	// modified. If err is not nil, typ represents the type that it should
	// have been had it been valid.
	emit func(offset int, typ byte, v []byte, err error) error

	// parser state
	cur    byte
	tok    byte // current token, '{', '[', '"', '1', 't', 'f', 'n'
	keyVal byte // when in an object, indicates if we're on key (':') or value (',')
	pos    int
	stack  stack
}

func (p *parser) parse() error {
	for p.cur != eof {
		p.skipWhitespace()

		var (
			typ byte
			err error
		)

		start := p.pos
		typ = p.cur
		p.advance()
		switch typ {
		case '{':
			p.stack.push(typ)
		case '[':
			p.stack.push(typ)
		case '"':
			//err = p.scanString()
		case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
			first := typ
			typ = '1'
			//err = p.scanNumber(first)
		case 't':
			err = p.scanLiteral(trueTrail)
		case 'f':
			err = p.scanLiteral(falseTrail)
		case 'n':
			err = p.scanLiteral(nullTrail)

		default:
			err = fmt.Errorf("invalid character: %#U", typ)
		}

		if e := p.emit(start, typ, p.input[start:p.pos], err); e != nil {
			return e
		}
	}
	return p.emit(p.pos, p.cur, nil, io.EOF)
}

func (p *parser) scanLiteral(trail string) error {
	for _, b := range []byte(trail) {
		if p.cur != b {
			return ErrIncompleteLiteral
		}
		p.advance()
	}
	return nil
}

func (p *parser) advance() {
	if p.pos >= len(p.input)-1 {
		p.pos++
		p.cur = eof
		return
	}
	p.pos++
	p.cur = p.input[p.pos]
}

func (p *parser) skipWhitespace() {
	for p.cur == '\t' || p.cur == '\r' || p.cur == '\n' || p.cur == ' ' {
		p.advance()
	}
}