forked from rosedblabs/rosedb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.go
520 lines (463 loc) · 13.7 KB
/
list.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
package rosedb
import (
"bytes"
"encoding/binary"
"github.com/flower-corp/rosedb/ds/art"
"github.com/flower-corp/rosedb/logfile"
"github.com/flower-corp/rosedb/logger"
"math"
)
// LPush insert all the specified values at the head of the list stored at key.
// If key does not exist, it is created as empty list before performing the push operations.
func (db *RoseDB) LPush(key []byte, values ...[]byte) error {
db.listIndex.mu.Lock()
defer db.listIndex.mu.Unlock()
if db.listIndex.trees[string(key)] == nil {
db.listIndex.trees[string(key)] = art.NewART()
}
for _, val := range values {
if err := db.pushInternal(key, val, true); err != nil {
return err
}
}
return nil
}
// LPushX insert specified values at the head of the list stored at key,
// only if key already exists and holds a list.
// In contrary to LPUSH, no operation will be performed when key does not yet exist.
func (db *RoseDB) LPushX(key []byte, values ...[]byte) error {
db.listIndex.mu.Lock()
defer db.listIndex.mu.Unlock()
if db.listIndex.trees[string(key)] == nil {
return ErrKeyNotFound
}
for _, val := range values {
if err := db.pushInternal(key, val, true); err != nil {
return err
}
}
return nil
}
// RPush insert all the specified values at the tail of the list stored at key.
// If key does not exist, it is created as empty list before performing the push operation.
func (db *RoseDB) RPush(key []byte, values ...[]byte) error {
db.listIndex.mu.Lock()
defer db.listIndex.mu.Unlock()
if db.listIndex.trees[string(key)] == nil {
db.listIndex.trees[string(key)] = art.NewART()
}
for _, val := range values {
if err := db.pushInternal(key, val, false); err != nil {
return err
}
}
return nil
}
// RPushX insert specified values at the tail of the list stored at key,
// only if key already exists and holds a list.
// In contrary to RPUSH, no operation will be performed when key does not yet exist.
func (db *RoseDB) RPushX(key []byte, values ...[]byte) error {
db.listIndex.mu.Lock()
defer db.listIndex.mu.Unlock()
if db.listIndex.trees[string(key)] == nil {
return ErrKeyNotFound
}
for _, val := range values {
if err := db.pushInternal(key, val, false); err != nil {
return err
}
}
return nil
}
// LPop removes and returns the first elements of the list stored at key.
func (db *RoseDB) LPop(key []byte) ([]byte, error) {
db.listIndex.mu.Lock()
defer db.listIndex.mu.Unlock()
return db.popInternal(key, true)
}
// RPop Removes and returns the last elements of the list stored at key.
func (db *RoseDB) RPop(key []byte) ([]byte, error) {
db.listIndex.mu.Lock()
defer db.listIndex.mu.Unlock()
return db.popInternal(key, false)
}
// LMove atomically returns and removes the first/last element of the list stored at source,
// and pushes the element at the first/last element of the list stored at destination.
func (db *RoseDB) LMove(srcKey, dstKey []byte, srcIsLeft, dstIsLeft bool) ([]byte, error) {
db.listIndex.mu.Lock()
defer db.listIndex.mu.Unlock()
popValue, err := db.popInternal(srcKey, srcIsLeft)
if err != nil {
return nil, err
}
if popValue == nil {
return nil, nil
}
if db.listIndex.trees[string(dstKey)] == nil {
db.listIndex.trees[string(dstKey)] = art.NewART()
}
if err = db.pushInternal(dstKey, popValue, dstIsLeft); err != nil {
return nil, err
}
return popValue, nil
}
// LLen returns the length of the list stored at key.
// If key does not exist, it is interpreted as an empty list and 0 is returned.
func (db *RoseDB) LLen(key []byte) int {
db.listIndex.mu.RLock()
defer db.listIndex.mu.RUnlock()
if db.listIndex.trees[string(key)] == nil {
return 0
}
idxTree := db.listIndex.trees[string(key)]
headSeq, tailSeq, err := db.listMeta(idxTree, key)
if err != nil {
return 0
}
return int(tailSeq - headSeq - 1)
}
// LIndex returns the element at index in the list stored at key.
// If index is out of range, it returns nil.
func (db *RoseDB) LIndex(key []byte, index int) ([]byte, error) {
db.listIndex.mu.RLock()
defer db.listIndex.mu.RUnlock()
if db.listIndex.trees[string(key)] == nil {
return nil, nil
}
idxTree := db.listIndex.trees[string(key)]
headSeq, tailSeq, err := db.listMeta(idxTree, key)
if err != nil {
return nil, err
}
seq, err := db.listSequence(headSeq, tailSeq, index)
if err != nil {
return nil, err
}
if seq >= tailSeq || seq <= headSeq {
return nil, ErrWrongIndex
}
encKey := db.encodeListKey(key, seq)
val, err := db.getVal(idxTree, encKey, List)
if err != nil {
return nil, err
}
return val, nil
}
// LSet Sets the list element at index to element.
func (db *RoseDB) LSet(key []byte, index int, value []byte) error {
db.listIndex.mu.Lock()
defer db.listIndex.mu.Unlock()
if db.listIndex.trees[string(key)] == nil {
return ErrKeyNotFound
}
idxTree := db.listIndex.trees[string(key)]
headSeq, tailSeq, err := db.listMeta(idxTree, key)
if err != nil {
return err
}
seq, err := db.listSequence(headSeq, tailSeq, index)
if err != nil {
return err
}
if seq >= tailSeq || seq <= headSeq {
return ErrWrongIndex
}
encKey := db.encodeListKey(key, seq)
ent := &logfile.LogEntry{Key: encKey, Value: value}
valuePos, err := db.writeLogEntry(ent, List)
if err != nil {
return err
}
if err = db.updateIndexTree(idxTree, ent, valuePos, true, List); err != nil {
return err
}
return nil
}
// LRange returns the specified elements of the list stored at key.
// The offsets start and stop are zero-based indexes, with 0 being the first element
// of the list (the head of the list), 1 being the next element and so on.
// These offsets can also be negative numbers indicating offsets starting at the end of the list.
// For example, -1 is the last element of the list, -2 the penultimate, and so on.
// If start is larger than the end of the list, an empty list is returned.
// If stop is larger than the actual end of the list, Redis will treat it like the last element of the list.
func (db *RoseDB) LRange(key []byte, start, end int) (values [][]byte, err error) {
db.listIndex.mu.RLock()
defer db.listIndex.mu.RUnlock()
if db.listIndex.trees[string(key)] == nil {
return nil, ErrKeyNotFound
}
idxTree := db.listIndex.trees[string(key)]
// get List DataType meta info
headSeq, tailSeq, err := db.listMeta(idxTree, key)
if err != nil {
return nil, err
}
var startSeq, endSeq uint32
// logical address to physical address
startSeq, err = db.listSequence(headSeq, tailSeq, start)
if err != nil {
return nil, err
}
endSeq, err = db.listSequence(headSeq, tailSeq, end)
if err != nil {
return nil, err
}
// normalize startSeq
if startSeq <= headSeq {
startSeq = headSeq + 1
}
// normalize endSeq
if endSeq >= tailSeq {
endSeq = tailSeq - 1
}
if startSeq >= tailSeq || endSeq <= headSeq || startSeq > endSeq {
return nil, ErrWrongIndex
}
// the endSeq value is included
for seq := startSeq; seq < endSeq+1; seq++ {
encKey := db.encodeListKey(key, seq)
val, err := db.getVal(idxTree, encKey, List)
if err != nil {
return nil, err
}
values = append(values, val)
}
return values, nil
}
func (db *RoseDB) encodeListKey(key []byte, seq uint32) []byte {
buf := make([]byte, len(key)+4)
binary.LittleEndian.PutUint32(buf[:4], seq)
copy(buf[4:], key[:])
return buf
}
func (db *RoseDB) decodeListKey(buf []byte) ([]byte, uint32) {
seq := binary.LittleEndian.Uint32(buf[:4])
key := make([]byte, len(buf[4:]))
copy(key[:], buf[4:])
return key, seq
}
func (db *RoseDB) listMeta(idxTree *art.AdaptiveRadixTree, key []byte) (uint32, uint32, error) {
val, err := db.getVal(idxTree, key, List)
if err != nil && err != ErrKeyNotFound {
return 0, 0, err
}
var headSeq uint32 = initialListSeq
var tailSeq uint32 = initialListSeq + 1
if len(val) != 0 {
headSeq = binary.LittleEndian.Uint32(val[:4])
tailSeq = binary.LittleEndian.Uint32(val[4:8])
}
return headSeq, tailSeq, nil
}
func (db *RoseDB) saveListMeta(idxTree *art.AdaptiveRadixTree, key []byte, headSeq, tailSeq uint32) error {
buf := make([]byte, 8)
binary.LittleEndian.PutUint32(buf[:4], headSeq)
binary.LittleEndian.PutUint32(buf[4:8], tailSeq)
ent := &logfile.LogEntry{Key: key, Value: buf, Type: logfile.TypeListMeta}
pos, err := db.writeLogEntry(ent, List)
if err != nil {
return err
}
err = db.updateIndexTree(idxTree, ent, pos, true, List)
return err
}
func (db *RoseDB) pushInternal(key []byte, val []byte, isLeft bool) error {
idxTree := db.listIndex.trees[string(key)]
headSeq, tailSeq, err := db.listMeta(idxTree, key)
if err != nil {
return err
}
var seq = headSeq
if !isLeft {
seq = tailSeq
}
encKey := db.encodeListKey(key, seq)
ent := &logfile.LogEntry{Key: encKey, Value: val}
valuePos, err := db.writeLogEntry(ent, List)
if err != nil {
return err
}
if err = db.updateIndexTree(idxTree, ent, valuePos, true, List); err != nil {
return err
}
if isLeft {
headSeq--
} else {
tailSeq++
}
err = db.saveListMeta(idxTree, key, headSeq, tailSeq)
return err
}
func (db *RoseDB) popInternal(key []byte, isLeft bool) ([]byte, error) {
if db.listIndex.trees[string(key)] == nil {
return nil, nil
}
idxTree := db.listIndex.trees[string(key)]
headSeq, tailSeq, err := db.listMeta(idxTree, key)
if err != nil {
return nil, err
}
if tailSeq-headSeq-1 <= 0 {
return nil, nil
}
var seq = headSeq + 1
if !isLeft {
seq = tailSeq - 1
}
encKey := db.encodeListKey(key, seq)
val, err := db.getVal(idxTree, encKey, List)
if err != nil {
return nil, err
}
ent := &logfile.LogEntry{Key: encKey, Type: logfile.TypeDelete}
pos, err := db.writeLogEntry(ent, List)
if err != nil {
return nil, err
}
oldVal, updated := idxTree.Delete(encKey)
if isLeft {
headSeq++
} else {
tailSeq--
}
if err = db.saveListMeta(idxTree, key, headSeq, tailSeq); err != nil {
return nil, err
}
// send discard
db.sendDiscard(oldVal, updated, List)
_, entrySize := logfile.EncodeEntry(ent)
node := &indexNode{fid: pos.fid, entrySize: entrySize}
select {
case db.discards[List].valChan <- node:
default:
logger.Warn("send to discard chan fail")
}
if tailSeq-headSeq-1 == 0 {
// reset meta
if headSeq != initialListSeq || tailSeq != initialListSeq+1 {
headSeq = initialListSeq
tailSeq = initialListSeq + 1
_ = db.saveListMeta(idxTree, key, headSeq, tailSeq)
}
delete(db.listIndex.trees, string(key))
}
return val, nil
}
// listSequence just convert logical index to physical seq.
// whether physical seq is legal or not, just convert it
func (db *RoseDB) listSequence(headSeq, tailSeq uint32, index int) (uint32, error) {
var seq uint32
if index >= 0 {
seq = headSeq + uint32(index) + 1
} else {
seq = tailSeq - uint32(-index)
}
return seq, nil
}
// LRem removes the first count occurrences of elements equal to element from the list stored at key.
// The count argument influences the operation in the following ways:
// count > 0: Remove elements equal to element moving from head to tail.
// count < 0: Remove elements equal to element moving from tail to head.
// count = 0: Remove all elements equal to element.
// Note that this method will rewrite the values, so it maybe very slow.
func (db *RoseDB) LRem(key []byte, count int, value []byte) (int, error) {
db.listIndex.mu.Lock()
defer db.listIndex.mu.Unlock()
if count == 0 {
count = math.MaxUint32
}
var discardCount int
idxTree := db.listIndex.trees[string(key)]
if idxTree == nil {
return discardCount, nil
}
// get List DataType meta info
headSeq, tailSeq, err := db.listMeta(idxTree, key)
if err != nil {
return discardCount, err
}
reserveSeq, discardSeq, reserveValueSeq := make([]uint32, 0), make([]uint32, 0), make([][]byte, 0)
classifyData := func(key []byte, seq uint32) error {
encKey := db.encodeListKey(key, seq)
val, err := db.getVal(idxTree, encKey, List)
if err != nil {
return err
}
if bytes.Equal(value, val) {
discardSeq = append(discardSeq, seq)
discardCount++
} else {
reserveSeq = append(reserveSeq, seq)
temp := make([]byte, len(val))
copy(temp, val)
reserveValueSeq = append(reserveValueSeq, temp)
}
return nil
}
addReserveData := func(key []byte, value []byte, isLeft bool) error {
if db.listIndex.trees[string(key)] == nil {
db.listIndex.trees[string(key)] = art.NewART()
}
if err := db.pushInternal(key, value, isLeft); err != nil {
return err
}
return nil
}
if count > 0 {
// record discard data and reserve data
for seq := headSeq + 1; seq < tailSeq; seq++ {
if err := classifyData(key, seq); err != nil {
return discardCount, err
}
if discardCount == count {
break
}
}
discardSeqLen := len(discardSeq)
if discardSeqLen > 0 {
// delete discard data
for seq := headSeq + 1; seq <= discardSeq[discardSeqLen-1]; seq++ {
if _, err := db.popInternal(key, true); err != nil {
return discardCount, err
}
}
// add reserve data
for i := len(reserveSeq) - 1; i >= 0; i-- {
if reserveSeq[i] < discardSeq[discardSeqLen-1] {
if err := addReserveData(key, reserveValueSeq[i], true); err != nil {
return discardCount, err
}
}
}
}
} else {
count = -count
// record discard data and reserve data
for seq := tailSeq - 1; seq > headSeq; seq-- {
if err := classifyData(key, seq); err != nil {
return discardCount, err
}
if discardCount == count {
break
}
}
discardSeqLen := len(discardSeq)
if discardSeqLen > 0 {
// delete discard data
for seq := tailSeq - 1; seq >= discardSeq[discardSeqLen-1]; seq-- {
if _, err := db.popInternal(key, false); err != nil {
return discardCount, err
}
}
// add reserve data
for i := len(reserveSeq) - 1; i >= 0; i-- {
if reserveSeq[i] > discardSeq[discardSeqLen-1] {
if err := addReserveData(key, reserveValueSeq[i], false); err != nil {
return discardCount, err
}
}
}
}
}
return discardCount, nil
}