-
Notifications
You must be signed in to change notification settings - Fork 2
/
stack.go
100 lines (86 loc) · 1.67 KB
/
stack.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
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
package jzon
import (
"sync"
)
var (
stackPool = sync.Pool{
New: func() interface{} {
return &stack{
stack: make([]uint64, 1),
}
},
}
)
type stackElement = int8
const (
stackElementNone stackElement = -1
stackElementObjectBegin stackElement = 0 // 0b00
stackElementObject stackElement = 2 // 0b10
stackElementArrayBegin stackElement = 1 // 0b01
stackElementArray stackElement = 3 // 0b11
)
type stack struct {
stack []uint64
depth uint
}
func (s *stack) init() *stack {
s.depth = 0
return s
}
func (s *stack) initObject() *stack {
if len(s.stack) == 0 {
s.stack = make([]uint64, 1)
}
s.stack[0] = 0
s.depth = 1
return s
}
func (s *stack) initArray() *stack {
if len(s.stack) == 0 {
s.stack = make([]uint64, 1)
}
s.stack[0] = 1
s.depth = 1
return s
}
func (s *stack) top() stackElement {
if s.depth == 0 {
return stackElementNone
}
depth := s.depth - 1
div := depth >> 6
mod := depth & 63
return stackElement((s.stack[div] >> mod) & 1)
}
func (s *stack) pop() stackElement {
if s.depth == 0 {
return stackElementNone
}
depth := s.depth - 1
div := depth >> 6
mod := depth & 63
s.depth--
// stackElementObjectBegin -> stackElementObject
// stackElementArrayBegin -> stackElementArray
return stackElement((s.stack[div]>>mod)&1) | 2
}
func (s *stack) pushObject() *stack {
div := s.depth >> 6
if div == uint(len(s.stack)) {
s.stack = append(s.stack, 0)
} else {
s.stack[div] &= (1 << (s.depth & 63)) - 1
}
s.depth++
return s
}
func (s *stack) pushArray() *stack {
div := s.depth >> 6
if div == uint(len(s.stack)) {
s.stack = append(s.stack, 1)
} else {
s.stack[div] |= 1 << (s.depth & 63)
}
s.depth++
return s
}