-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
110 lines (98 loc) · 2.27 KB
/
builder.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
101
102
103
104
105
106
107
108
109
110
package immutableList
type Builder interface {
Add(value Object) Builder
Size() int
Build() List
}
type leafBuilder struct {
parent *branchBuilder
count int // only zero if Add() has never been called
buffer [maxValuesPerLeaf]Object
}
type branchBuilder struct {
parent *branchBuilder
left node // never nil
right node // may be nil
}
func CreateBuilder() Builder {
return &leafBuilder{}
}
func (this *leafBuilder) Add(value Object) Builder {
if this.count == maxValuesPerLeaf {
leafNode := this.createLeafFromBuffer()
if this.parent == nil {
this.parent = createBranchBuilder(leafNode)
} else {
this.parent.addChild(leafNode)
}
this.buffer[0] = value
this.count = 1
} else {
this.buffer[this.count] = value
this.count += 1
}
return this
}
func (this *leafBuilder) Size() int {
answer := this.count
if this.parent != nil {
answer += this.parent.computeSize()
}
return answer
}
func (this *leafBuilder) Build() List {
var root node
if this.count == 0 {
root = createEmptyLeafNode()
} else if this.parent == nil {
root = this.createLeafFromBuffer()
} else {
root = this.parent.build(this.createLeafFromBuffer())
}
return createListNode(root)
}
func (this *leafBuilder) createLeafFromBuffer() node {
values := make([]Object, this.count)
copy(values[0:], this.buffer[0:this.count])
return createMultiValueLeafNode(values)
}
func createBranchBuilder(left node) *branchBuilder {
return &branchBuilder{left: left}
}
func (this *branchBuilder) addChild(node node) {
if this.right == nil {
this.right = node
} else {
branchNode := createBranchNode(this.left, this.right)
if this.parent == nil {
this.parent = createBranchBuilder(branchNode)
} else {
this.parent.addChild(branchNode)
}
this.left = node
this.right = nil
}
}
func (this *branchBuilder) build(extra node) node {
var answer node
if this.right == nil {
answer = this.left
} else {
answer = createBranchNode(this.left, this.right)
}
if this.parent != nil {
answer = this.parent.build(answer)
}
answer = answer.appendNode(extra)
return answer
}
func (this *branchBuilder) computeSize() int {
answer := this.left.size()
if this.right != nil {
answer += this.right.size()
}
if this.parent != nil {
answer += this.parent.computeSize()
}
return answer
}