forked from beeker1121/goque
-
Notifications
You must be signed in to change notification settings - Fork 0
/
priority_queue.go
563 lines (464 loc) · 14.1 KB
/
priority_queue.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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
package goque
import (
"bytes"
"encoding/gob"
"encoding/json"
"os"
"sync"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/util"
)
// prefixSep is the prefix separator for each item key.
var prefixSep []byte = []byte(":")
// order defines the priority ordering of the queue.
type order int
// Defines which priority order to dequeue in.
const (
ASC order = iota // Set priority level 0 as most important.
DESC // Set priority level 255 as most important.
)
// priorityLevel holds the head and tail position of a priority
// level within the queue.
type priorityLevel struct {
head uint64
tail uint64
}
// length returns the total number of items in this priority level.
func (pl *priorityLevel) length() uint64 {
return pl.tail - pl.head
}
// PriorityQueue is a standard FIFO (first in, first out) queue with
// priority levels.
type PriorityQueue struct {
sync.RWMutex
DataDir string
db *leveldb.DB
order order
levels [256]*priorityLevel
curLevel uint8
isOpen bool
}
// OpenPriorityQueue opens a priority queue if one exists at the given
// directory. If one does not already exist, a new priority queue is
// created.
func OpenPriorityQueue(dataDir string, order order) (*PriorityQueue, error) {
var err error
// Create a new PriorityQueue.
pq := &PriorityQueue{
DataDir: dataDir,
db: &leveldb.DB{},
order: order,
isOpen: false,
}
// Open database for the priority queue.
pq.db, err = leveldb.OpenFile(dataDir, nil)
if err != nil {
return pq, err
}
// Check if this Goque type can open the requested data directory.
ok, err := checkGoqueType(dataDir, goquePriorityQueue)
if err != nil {
return pq, err
}
if !ok {
return pq, ErrIncompatibleType
}
// Set isOpen and return.
pq.isOpen = true
return pq, pq.init()
}
// Enqueue adds an item to the priority queue.
func (pq *PriorityQueue) Enqueue(priority uint8, value []byte) (*PriorityItem, error) {
pq.Lock()
defer pq.Unlock()
// Check if queue is closed.
if !pq.isOpen {
return nil, ErrDBClosed
}
// Get the priorityLevel.
level := pq.levels[priority]
// Create new PriorityItem.
item := &PriorityItem{
ID: level.tail + 1,
Priority: priority,
Key: pq.generateKey(priority, level.tail+1),
Value: value,
}
// Add it to the priority queue.
if err := pq.db.Put(item.Key, item.Value, nil); err != nil {
return nil, err
}
// Increment tail position.
level.tail++
// If this priority level is more important than the curLevel.
if pq.cmpAsc(priority) || pq.cmpDesc(priority) {
pq.curLevel = priority
}
return item, nil
}
// EnqueueString is a helper function for Enqueue that accepts a
// value as a string rather than a byte slice.
func (pq *PriorityQueue) EnqueueString(priority uint8, value string) (*PriorityItem, error) {
return pq.Enqueue(priority, []byte(value))
}
// EnqueueObject is a helper function for Enqueue that accepts any
// value type, which is then encoded into a byte slice using
// encoding/gob.
//
// Objects containing pointers with zero values will decode to nil
// when using this function. This is due to how the encoding/gob
// package works. Because of this, you should only use this function
// to encode simple types.
func (pq *PriorityQueue) EnqueueObject(priority uint8, value interface{}) (*PriorityItem, error) {
var buffer bytes.Buffer
enc := gob.NewEncoder(&buffer)
if err := enc.Encode(value); err != nil {
return nil, err
}
return pq.Enqueue(priority, buffer.Bytes())
}
// EnqueueObjectAsJSON is a helper function for Enqueue that accepts
// any value type, which is then encoded into a JSON byte slice using
// encoding/json.
//
// Use this function to handle encoding of complex types.
func (pq *PriorityQueue) EnqueueObjectAsJSON(priority uint8, value interface{}) (*PriorityItem, error) {
jsonBytes, err := json.Marshal(value)
if err != nil {
return nil, err
}
return pq.Enqueue(priority, jsonBytes)
}
// Dequeue removes the next item in the priority queue and returns it.
func (pq *PriorityQueue) Dequeue() (*PriorityItem, error) {
pq.Lock()
defer pq.Unlock()
// Check if queue is closed.
if !pq.isOpen {
return nil, ErrDBClosed
}
// Try to get the next item.
item, err := pq.getNextItem()
if err != nil {
return nil, err
}
// Remove this item from the priority queue.
if err = pq.db.Delete(item.Key, nil); err != nil {
return nil, err
}
// Increment head position.
pq.levels[pq.curLevel].head++
return item, nil
}
// DequeueByPriority removes the next item in the given priority level
// and returns it.
func (pq *PriorityQueue) DequeueByPriority(priority uint8) (*PriorityItem, error) {
pq.Lock()
defer pq.Unlock()
// Check if queue is closed.
if !pq.isOpen {
return nil, ErrDBClosed
}
// Try to get the next item in the given priority level.
item, err := pq.getItemByPriorityID(priority, pq.levels[priority].head+1)
if err != nil {
return nil, err
}
// Remove this item from the priority queue.
if err = pq.db.Delete(item.Key, nil); err != nil {
return nil, err
}
// Increment head position.
pq.levels[priority].head++
return item, nil
}
// Peek returns the next item in the priority queue without removing it.
func (pq *PriorityQueue) Peek() (*PriorityItem, error) {
pq.RLock()
defer pq.RUnlock()
// Check if queue is closed.
if !pq.isOpen {
return nil, ErrDBClosed
}
return pq.getNextItem()
}
// PeekByOffset returns the item located at the given offset,
// starting from the head of the queue, without removing it.
func (pq *PriorityQueue) PeekByOffset(offset uint64) (*PriorityItem, error) {
pq.RLock()
defer pq.RUnlock()
// Check if queue is closed.
if !pq.isOpen {
return nil, ErrDBClosed
}
// Check if queue is empty.
if pq.Length() == 0 {
return nil, ErrEmpty
}
// If the offset is within the current priority level.
if pq.levels[pq.curLevel].length() >= offset+1 {
return pq.getItemByPriorityID(pq.curLevel, pq.levels[pq.curLevel].head+offset+1)
}
return pq.findOffset(offset)
}
// PeekByPriorityID returns the item with the given ID and priority without
// removing it.
func (pq *PriorityQueue) PeekByPriorityID(priority uint8, id uint64) (*PriorityItem, error) {
pq.RLock()
defer pq.RUnlock()
// Check if queue is closed.
if !pq.isOpen {
return nil, ErrDBClosed
}
return pq.getItemByPriorityID(priority, id)
}
// Update updates an item in the priority queue without changing its
// position.
func (pq *PriorityQueue) Update(priority uint8, id uint64, newValue []byte) (*PriorityItem, error) {
pq.Lock()
defer pq.Unlock()
// Check if queue is closed.
if !pq.isOpen {
return nil, ErrDBClosed
}
// Check if item exists in queue.
if id <= pq.levels[priority].head || id > pq.levels[priority].tail {
return nil, ErrOutOfBounds
}
// Create new PriorityItem.
item := &PriorityItem{
ID: id,
Priority: priority,
Key: pq.generateKey(priority, id),
Value: newValue,
}
// Update this item in the queue.
if err := pq.db.Put(item.Key, item.Value, nil); err != nil {
return nil, err
}
return item, nil
}
// UpdateString is a helper function for Update that accepts a value
// as a string rather than a byte slice.
func (pq *PriorityQueue) UpdateString(priority uint8, id uint64, newValue string) (*PriorityItem, error) {
return pq.Update(priority, id, []byte(newValue))
}
// UpdateObject is a helper function for Update that accepts any
// value type, which is then encoded into a byte slice using
// encoding/gob.
//
// Objects containing pointers with zero values will decode to nil
// when using this function. This is due to how the encoding/gob
// package works. Because of this, you should only use this function
// to encode simple types.
func (pq *PriorityQueue) UpdateObject(priority uint8, id uint64, newValue interface{}) (*PriorityItem, error) {
var buffer bytes.Buffer
enc := gob.NewEncoder(&buffer)
if err := enc.Encode(newValue); err != nil {
return nil, err
}
return pq.Update(priority, id, buffer.Bytes())
}
// UpdateObjectAsJSON is a helper function for Update that accepts
// any value type, which is then encoded into a JSON byte slice using
// encoding/json.
//
// Use this function to handle encoding of complex types.
func (pq *PriorityQueue) UpdateObjectAsJSON(priority uint8, id uint64, newValue interface{}) (*PriorityItem, error) {
jsonBytes, err := json.Marshal(newValue)
if err != nil {
return nil, err
}
return pq.Update(priority, id, jsonBytes)
}
// Length returns the total number of items in the priority queue.
func (pq *PriorityQueue) Length() uint64 {
pq.RLock()
defer pq.RUnlock()
var length uint64
for _, v := range pq.levels {
length += v.length()
}
return length
}
// Close closes the LevelDB database of the priority queue.
func (pq *PriorityQueue) Close() error {
pq.Lock()
defer pq.Unlock()
// Check if queue is already closed.
if !pq.isOpen {
return nil
}
// Close the LevelDB database.
if err := pq.db.Close(); err != nil {
return err
}
// Reset head and tail of each priority level
// and set isOpen to false.
for i := 0; i <= 255; i++ {
pq.levels[uint8(i)].head = 0
pq.levels[uint8(i)].tail = 0
}
pq.isOpen = false
return nil
}
// Drop closes and deletes the LevelDB database of the priority queue.
func (pq *PriorityQueue) Drop() error {
if err := pq.Close(); err != nil {
return err
}
return os.RemoveAll(pq.DataDir)
}
// cmpAsc returns wehther the given priority level is higher than the
// current priority level based on ascending order.
func (pq *PriorityQueue) cmpAsc(priority uint8) bool {
return pq.order == ASC && priority < pq.curLevel
}
// cmpAsc returns wehther the given priority level is higher than the
// current priority level based on descending order.
func (pq *PriorityQueue) cmpDesc(priority uint8) bool {
return pq.order == DESC && priority > pq.curLevel
}
// resetCurrentLevel resets the current priority level of the queue
// so the highest level can be found.
func (pq *PriorityQueue) resetCurrentLevel() {
if pq.order == ASC {
pq.curLevel = 255
} else if pq.order == DESC {
pq.curLevel = 0
}
}
// findOffset finds the given offset from the current queue position
// based on priority order.
func (pq *PriorityQueue) findOffset(offset uint64) (*PriorityItem, error) {
var length uint64
var curLevel uint8 = pq.curLevel
var newLevel int
// Handle newLevel initialization for descending order.
if pq.order == DESC {
newLevel = 255
}
// For condition expression.
condExpr := func(level int) bool {
if pq.order == ASC {
return level <= 255
}
return level >= 0
}
// For loop expression.
loopExpr := func(level *int) {
if pq.order == ASC {
*level++
} else if pq.order == DESC {
*level--
}
}
// Level comparison.
cmpLevels := func(newLevel, curLevel uint8) bool {
if pq.order == ASC {
return newLevel >= curLevel
}
return newLevel <= curLevel
}
// Loop through the priority levels.
for ; condExpr(newLevel); loopExpr(&newLevel) {
// If this level is lower than the current level based on ordering and contains items.
if cmpLevels(uint8(newLevel), curLevel) && pq.levels[uint8(newLevel)].length() > 0 {
curLevel = uint8(newLevel)
newLength := pq.levels[curLevel].length()
// If the offset is within the current priority level.
if length+newLength >= offset+1 {
return pq.getItemByPriorityID(curLevel, offset-length+1)
}
length += newLength
}
}
return nil, ErrOutOfBounds
}
// getNextItem returns the next item in the priority queue, updating
// the current priority level of the queue if necessary.
func (pq *PriorityQueue) getNextItem() (*PriorityItem, error) {
// If the current priority level is empty.
if pq.levels[pq.curLevel].length() == 0 {
// Set starting value for curLevel.
pq.resetCurrentLevel()
// Try to get the next priority level.
for i := 0; i <= 255; i++ {
if (pq.cmpAsc(uint8(i)) || pq.cmpDesc(uint8(i))) && pq.levels[uint8(i)].length() > 0 {
pq.curLevel = uint8(i)
}
}
// If still empty, return queue empty error.
if pq.levels[pq.curLevel].length() == 0 {
return nil, ErrEmpty
}
}
// Try to get the next item in the current priority level.
return pq.getItemByPriorityID(pq.curLevel, pq.levels[pq.curLevel].head+1)
}
// getItemByID returns an item, if found, for the given ID.
func (pq *PriorityQueue) getItemByPriorityID(priority uint8, id uint64) (*PriorityItem, error) {
// Check if empty or out of bounds.
if pq.levels[priority].length() == 0 {
return nil, ErrEmpty
} else if id <= pq.levels[priority].head || id > pq.levels[priority].tail {
return nil, ErrOutOfBounds
}
// Get item from database.
var err error
item := &PriorityItem{ID: id, Priority: priority, Key: pq.generateKey(priority, id)}
if item.Value, err = pq.db.Get(item.Key, nil); err != nil {
return nil, err
}
return item, nil
}
// generatePrefix creates the key prefix for the given priority level.
func (pq *PriorityQueue) generatePrefix(level uint8) []byte {
// priority + prefixSep = 1 + 1 = 2
prefix := make([]byte, 2)
prefix[0] = byte(level)
prefix[1] = prefixSep[0]
return prefix
}
// generateKey create a key to be used with LevelDB.
func (pq *PriorityQueue) generateKey(priority uint8, id uint64) []byte {
// prefix + key = 2 + 8 = 10
key := make([]byte, 10)
copy(key[0:2], pq.generatePrefix(priority))
copy(key[2:], idToKey(id))
return key
}
// init initializes the priority queue data.
func (pq *PriorityQueue) init() error {
// Set starting value for curLevel.
pq.resetCurrentLevel()
// Loop through each priority level.
for i := 0; i <= 255; i++ {
// Create a new LevelDB Iterator for this priority level.
prefix := pq.generatePrefix(uint8(i))
iter := pq.db.NewIterator(util.BytesPrefix(prefix), nil)
// Create a new priorityLevel.
pl := &priorityLevel{
head: 0,
tail: 0,
}
// Set priority level head to the first item.
if iter.First() {
pl.head = keyToID(iter.Key()[2:]) - 1
// Since this priority level has item(s), handle updating curLevel.
if pq.cmpAsc(uint8(i)) || pq.cmpDesc(uint8(i)) {
pq.curLevel = uint8(i)
}
}
// Set priority level tail to the last item.
if iter.Last() {
pl.tail = keyToID(iter.Key()[2:])
}
if iter.Error() != nil {
return iter.Error()
}
pq.levels[i] = pl
iter.Release()
}
return nil
}