-
Notifications
You must be signed in to change notification settings - Fork 0
/
pricelist.go
102 lines (86 loc) · 1.99 KB
/
pricelist.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
package orderbook
import (
"context"
"fmt"
pool "github.com/jolestar/go-commons-pool"
"github.com/ldmtam/skiplist"
)
// PriceItem ...
type PriceItem struct {
Price int
Orders *OrderQueue
}
// ItemIterator ...
type ItemIterator func(i *PriceItem) bool
// PriceList ...
type PriceList struct {
l skiplist.SkipList
orderQueuePool *pool.ObjectPool
}
// ExtractKey ...
func (item *PriceItem) ExtractKey() float64 {
return float64(item.Price)
}
func (item *PriceItem) String() string {
return fmt.Sprintf("price: %d", item.Price)
}
// NewPriceList ...
func NewPriceList(orderQueuePool *pool.ObjectPool) *PriceList {
l := skiplist.New()
return &PriceList{
l: l,
orderQueuePool: orderQueuePool,
}
}
// GetItem ...
func (pl *PriceList) GetItem(price int) *PriceItem {
elem, ok := pl.l.FindByKey(float64(price))
if ok {
return elem.GetValue().(*PriceItem)
}
obj, err := pl.orderQueuePool.BorrowObject(context.Background())
if err != nil {
panic("cannot get object from pool")
}
item := &PriceItem{
Price: price,
Orders: obj.(*OrderQueue),
}
pl.l.Insert(item)
return item
}
// Delete ...
func (pl *PriceList) Delete(price int) {
elem, ok := pl.l.FindByKey(float64(price))
if !ok {
return
}
pl.orderQueuePool.ReturnObject(context.Background(), elem.GetValue().(*PriceItem).Orders)
pl.l.Delete(elem.GetValue().(*PriceItem))
}
// Ascend ...
func (pl *PriceList) Ascend(iterator ItemIterator) {
if pl.l.IsEmpty() {
return
}
smallestElem := pl.l.GetSmallestNode()
for elem := smallestElem; elem != nil; elem = pl.l.Next(elem) {
item := elem.GetValue().(*PriceItem)
if !iterator(item) || pl.l.Next(elem) == smallestElem {
break
}
}
}
// Descend ...
func (pl *PriceList) Descend(iterator ItemIterator) {
if pl.l.IsEmpty() {
return
}
largestElem := pl.l.GetLargestNode()
for elem := largestElem; elem != nil; elem = pl.l.Prev(elem) {
item := elem.GetValue().(*PriceItem)
if !iterator(item) || pl.l.Prev(elem) == largestElem {
break
}
}
}