forked from supranational/blst
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rb_tree.go
149 lines (123 loc) · 3.31 KB
/
rb_tree.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
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
/*
* Copyright Supranational LLC
* Licensed under the Apache License, Version 2.0, see LICENSE for details.
* SPDX-License-Identifier: Apache-2.0
*/
/*
* Reimplement rb_tree.c, because C.call overhead is too high in
* comparison to tree insertion subroutine.
*/
package blst
import "bytes"
/*
* Red-black tree tailored for uniqueness test. Amount of messages to be
* checked is known prior context initialization, implementation is
* insert-only, failure is returned if message is already in the tree.
*/
const red, black bool = true, false
type node struct {
leafs [2]*node
data *[]byte
colour bool
}
type rbTree struct {
root *node
nnodes uint
nodes []node
}
func (tree *rbTree) insert(data *[]byte) bool {
var nodes [64]*node /* visited nodes */
var dirs [64]byte /* taken directions */
var k uint /* walked distance */
for p := tree.root; p != nil; k++ {
cmp := bytes.Compare(*data, *p.data)
if cmp == 0 {
return false /* already in tree, no insertion */
}
/* record the step */
nodes[k] = p
if cmp > 0 {
dirs[k] = 1
} else {
dirs[k] = 0
}
p = p.leafs[dirs[k]]
}
/* allocate new node */
z := &tree.nodes[tree.nnodes]; tree.nnodes++
z.data = data
z.colour = red
/* graft |z| */
if k > 0 {
nodes[k-1].leafs[dirs[k-1]] = z
} else {
tree.root = z
}
/* re-balance |tree| */
for k >= 2 /* && IS_RED(y = nodes[k-1]) */ {
y := nodes[k-1]
if y.colour == black { // nolint:gosimple
break
}
ydir := dirs[k-2]
x := nodes[k-2] /* |z|'s grandparent */
s := x.leafs[ydir^1] /* |z|'s uncle */
if s != nil && s.colour == red { // nolint:gosimple
x.colour = red
y.colour = black
s.colour = black
k -= 2
} else {
if dirs[k-1] != ydir {
/* | |
* x x
* / \ \
* y s -> z s
* \ /
* z y
* / \
* ? ?
*/
t := y
y = y.leafs[ydir^1]
t.leafs[ydir^1] = y.leafs[ydir]
y.leafs[ydir] = t
}
/* | |
* x y
* \ / \
* y s -> z x
* / \ / \
* z ? ? s
*/
x.leafs[ydir] = y.leafs[ydir^1]
y.leafs[ydir^1] = x
x.colour = red
y.colour = black
if k > 2 {
nodes[k-3].leafs[dirs[k-3]] = y
} else {
tree.root = y
}
break
}
}
tree.root.colour = black
return true
}
func Uniq(msgs []Message) bool {
n := len(msgs)
if n == 1 {
return true
} else if n == 2 {
return !bytes.Equal(msgs[0], msgs[1])
}
var tree rbTree
tree.nodes = make([]node, n)
for i := 0; i < n; i++ {
if !tree.insert(&msgs[i]) {
return false
}
}
return true
}