forked from xiejingfa/the-annotated-redis-3.0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
t_zset.c
3465 lines (3061 loc) · 128 KB
/
t_zset.c
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
* Copyright (c) 2009-2012, Pieter Noordhuis <pcnoordhuis at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*-----------------------------------------------------------------------------
* Sorted set API
*----------------------------------------------------------------------------*/
/* ZSETs are ordered sets using two data structures to hold the same elements
* in order to get O(log(N)) INSERT and REMOVE operations into a sorted
* data structure.
*
* ZSET使用两种结构来有序地保存同一元素从而提供O(log(N))复杂度的插入和删除操作。
*
* The elements are added to a hash table mapping Redis objects to scores.
* At the same time the elements are added to a skip list mapping scores
* to Redis objects (so objects are sorted by scores in this "view").
*
* 元素被添加到哈希表中,这个哈希表维持着Redis对象到分值score的映射关系。同时该元素也添加到跳跃表中,
* 跳跃表维持着分值score到Redis对象的映射关系。这样ZSET就(给用户)提供了一种按分值score排序的视图。
*/
/* This skiplist implementation is almost a C translation of the original
* algorithm described by William Pugh in "Skip Lists: A Probabilistic
* Alternative to Balanced Trees", modified in three ways:
* a) this implementation allows for repeated scores.
* b) the comparison is not just by key (our 'score') but by satellite data.
* c) there is a back pointer, so it's a doubly linked list with the back
* pointers being only at "level 1". This allows to traverse the list
* from tail to head, useful for ZREVRANGE.
*
* Redis中的跳跃表实现和William Pugh在《Skip Lists: A Probabilistic Alternative to Balanced Trees》
* 一文中描述的跳跃表基本一致,主要有以下三点改进:
* (1)、Redis中的跳跃表允许有重复的分值score。
* (2)、节点的比较操作不仅仅比较其分值score,同时还要比较其关联的元素值。
* (3)、每个节点还有一个后退指针(相当于双向链表中的prev指针),通个该指针,我们可以从表尾向表头遍历列表。
* 从这点看,跳跃表的第一层是一个双向链表。
*/
#include "redis.h"
#include <math.h>
static int zslLexValueGteMin(robj *value, zlexrangespec *spec);
static int zslLexValueLteMax(robj *value, zlexrangespec *spec);
/* 创建一个层数为level的跳跃表节点,并设置该节点的分值、元素值。*/
zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
// zskiplistNode中的level数组并不是固定大小的,而是可变大小的,每次创建节点需要动态计算
// level*sizeof(struct zskiplistLevel)为level[]所占用空间
zskiplistNode *zn = zmalloc(sizeof(*zn)+level*sizeof(struct zskiplistLevel));
// 设置分值、节点数据
zn->score = score;
zn->obj = obj;
// 返回节点指针
return zn;
}
/* 创建一个跳跃表 */
zskiplist *zslCreate(void) {
int j;
zskiplist *zsl;
// 分配空间
zsl = zmalloc(sizeof(*zsl));
// 当前最大层数为1,节点数量为0
zsl->level = 1;
zsl->length = 0;
// 列表的初始化需要初始化头部,并使头部每层(根据事先定义的ZSKIPLIST_MAXLEVEL)指向末尾(NULL)
// ZSKIPLIST_MAXLEVEL的默认值为32
zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
zsl->header->level[j].forward = NULL;
zsl->header->level[j].span = 0;
}
// 对于以个空跳跃表,backward指针也为空
zsl->header->backward = NULL;
zsl->tail = NULL;
return zsl;
}
/* 释放指定的跳跃表节点 */
void zslFreeNode(zskiplistNode *node) {
decrRefCount(node->obj);
zfree(node);
}
/* 释放跳跃表 */
void zslFree(zskiplist *zsl) {
zskiplistNode *node = zsl->header->level[0].forward, *next;
// 释放表头
zfree(zsl->header);
// 逐一释放每个节点
while(node) {
next = node->level[0].forward;
zslFreeNode(node);
node = next;
}
zfree(zsl);
}
/* Returns a random level for the new skiplist node we are going to create.
* The return value of this function is between 1 and ZSKIPLIST_MAXLEVEL
* (both inclusive), with a powerlaw-alike distribution where higher
* levels are less likely to be returned. */
/* 返回一个随机值作为跳跃表新节点的层数。 该随机值的数值范围是[1, ZSKIPLIST_MAXLEVEL]。
该函数使用了powerlaw-alike的方法,能够保证越大的值生成的概率越小。
跳表是一种随机化数据结构,其随机化体现在插入元素的时候元素所占有的层数完全是随机的,层数是通过随机算法产生的
*/
int zslRandomLevel(void) {
int level = 1;
while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
level += 1;
return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
}
/* 往跳跃表中插入一个新节点,新节点的分值为score、保存的元素值为obj。*/
zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj) {
// update数组用来保存降层节点指针
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
// 记录沿途跨越的节点数,用来计算新节点的span值
unsigned int rank[ZSKIPLIST_MAXLEVEL];
int i, level;
redisAssert(!isnan(score));
x = zsl->header;
// 从高到底在各层中查找插入位置
for (i = zsl->level-1; i >= 0; i--) {
/* store rank that is crossed to reach the insert position */
rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
// 在当前层找到一个下降节点,并将其指针保存在update数组中
while (x->level[i].forward &&
(x->level[i].forward->score < score ||
(x->level[i].forward->score == score &&
compareStringObjects(x->level[i].forward->obj,obj) < 0))) {
// 记录跨越的节点数
rank[i] += x->level[i].span;
x = x->level[i].forward;
}
// update[i]就是要和新节点直接相连的节点
update[i] = x;
}
/* we assume the key is not already inside, since we allow duplicated
* scores, and the re-insertion of score and redis object should never
* happen since the caller of zslInsert() should test in the hash table
* if the element is already inside or not. */
// 由调用者保证不会插入相同分值和相同成员的元素,所以这里不需要检查
level = zslRandomLevel();
// 如果新节点的层数比目前其它节点的层数都要大,那么表头节点header就会存在一些未初始化的层,
// 这里将他们记录在update数组中,方便后面处理
if (level > zsl->level) {
for (i = zsl->level; i < level; i++) {
rank[i] = 0;
update[i] = zsl->header;
update[i]->level[i].span = zsl->length;
}
// 更新当前最大层数
zsl->level = level;
}
// 创建新节点
x = zslCreateNode(level,score,obj);
// 从低往高逐层更新节点指针,类似于链表的插入
for (i = 0; i < level; i++) {
// 设置新节点的forward指针,指向原节点的下一个节点
x->level[i].forward = update[i]->level[i].forward;
// 让原节点的forward指针指向新节点
update[i]->level[i].forward = x;
/* update span covered by update[i] as x is inserted here */
// 更新新节点跨越的节点数量
x->level[i].span = update[i]->level[i].span - (rank[0] - rank[i]);
update[i]->level[i].span = (rank[0] - rank[i]) + 1;
}
/* increment span for untouched levels */
for (i = level; i < zsl->level; i++) {
update[i]->level[i].span++;
}
// 更新新节点的backward指针
x->backward = (update[0] == zsl->header) ? NULL : update[0];
// 更新新节点下一个节点的backward指针
if (x->level[0].forward)
x->level[0].forward->backward = x;
else
zsl->tail = x;
// 增加了一个新节点
zsl->length++;
return x;
}
/* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
/* 删除节点函数,供zslDelete、zslDeleteByScore和zslDeleteByRank函数调用 */
void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
int i;
// 从低往高,逐层删除x节点,只要简单地修改指针指向即可,和链表删除节点类似
for (i = 0; i < zsl->level; i++) {
if (update[i]->level[i].forward == x) {
update[i]->level[i].span += x->level[i].span - 1;
update[i]->level[i].forward = x->level[i].forward;
} else {
update[i]->level[i].span -= 1;
}
}
// 更新被删除节点x的backward指针
if (x->level[0].forward) {
x->level[0].forward->backward = x->backward;
} else {
zsl->tail = x->backward;
}
// 如果该节点的level是最大的,则需要更新跳表的level
while(zsl->level > 1 && zsl->header->level[zsl->level-1].forward == NULL)
zsl->level--;
// 跳跃表节点个数减1
zsl->length--;
}
/* Delete an element with matching score/object from the skiplist. */
/* 从从跳跃表中删除一个分值score、元素值为obj的节点。 */
int zslDelete(zskiplist *zsl, double score, robj *obj) {
/* 下面这个过程和zslInsert类似,*/
// update数组用来保存降层节点指针
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
int i;
// 从高往低逐层查找目标节点,并把降层节点指针保存在update中
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
while (x->level[i].forward &&
(x->level[i].forward->score < score ||
// 既比较分值score又比较节点对象
(x->level[i].forward->score == score &&
compareStringObjects(x->level[i].forward->obj,obj) < 0)))
x = x->level[i].forward;
update[i] = x;
}
/* We may have multiple elements with the same score, what we need
* is to find the element with both the right score and object. */
// 跳跃表中可能存在重复的分值,只有在分值score和元素值obj都相等的节点才是正在要删除的节点
x = x->level[0].forward;
if (x && score == x->score && equalStringObjects(x->obj,obj)) {
// 删除节点
zslDeleteNode(zsl, x, update);
// 释放空间
zslFreeNode(x);
return 1;
}
return 0; /* not found */
}
/* 判断一个给定值value是否大于或者大于等于spec中的min值。
zrangespec定义在redis.h文件中,表示一个开区间/闭区间。 */
static int zslValueGteMin(double value, zrangespec *spec) {
return spec->minex ? (value > spec->min) : (value >= spec->min);
}
/* 判断一个给定值value是否小于或小于等于spec中的max值。
zrangespec定义在redis.h文件中,表示一个开区间/闭区间。 */
static int zslValueLteMax(double value, zrangespec *spec) {
return spec->maxex ? (value < spec->max) : (value <= spec->max);
}
/* Returns if there is a part of the zset is in range. */
/* 如果range给定的数值范围包含在跳跃表的分值范围则返回1,否则返回0。*/
int zslIsInRange(zskiplist *zsl, zrangespec *range) {
zskiplistNode *x;
/* Test for ranges that will always be empty. */
// 验证range指定的范围是否为空
if (range->min > range->max ||
(range->min == range->max && (range->minex || range->maxex)))
return 0;
// 检查跳跃表中的最大分值score
x = zsl->tail;
if (x == NULL || !zslValueGteMin(x->score,range))
return 0;
// 检查跳跃表中的最小分值score
x = zsl->header->level[0].forward;
if (x == NULL || !zslValueLteMax(x->score,range))
return 0;
return 1;
}
/* Find the first node that is contained in the specified range.
* Returns NULL when no element is contained in the range. */
/* 返回跳跃表中第一个分值score在range指定范围的节点,如果没有一个节点符合要求则返回NULL。*/
zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec *range) {
zskiplistNode *x;
int i;
/* If everything is out of range, return early. */
// 如果给定range不包含在跳跃表的分值范围内,马上返回
if (!zslIsInRange(zsl,range)) return NULL;
x = zsl->header;
// 从前往后遍历跳跃表,查找第一个分值落在range指定范围的节点
for (i = zsl->level-1; i >= 0; i--) {
/* Go forward while *OUT* of range. */
while (x->level[i].forward &&
!zslValueGteMin(x->level[i].forward->score,range))
x = x->level[i].forward;
}
/* This is an inner range, so the next node cannot be NULL. */
// 找到第一层中的目标节点
x = x->level[0].forward;
redisAssert(x != NULL);
/* Check if score <= max. */
// 最后还要检查当前节点的分值是否超出range的右边界,即score <= max
if (!zslValueLteMax(x->score,range)) return NULL;
return x;
}
/* Find the last node that is contained in the specified range.
* Returns NULL when no element is contained in the range. */
/* 返回跳跃表中最后一个分值score在range指定范围的节点,如果没有一个节点符合要求则返回NULL。*/
zskiplistNode *zslLastInRange(zskiplist *zsl, zrangespec *range) {
zskiplistNode *x;
int i;
/* If everything is out of range, return early. */
// 同样,如果给定range不包含在跳跃表的分值范围内,马上返回
if (!zslIsInRange(zsl,range)) return NULL;
x = zsl->header;
// 从前往后遍历遍历跳跃表,查找最后一个分值小于或小于等于range.max的节点
for (i = zsl->level-1; i >= 0; i--) {
/* Go forward while *IN* range. */
while (x->level[i].forward &&
zslValueLteMax(x->level[i].forward->score,range))
x = x->level[i].forward;
}
/* This is an inner range, so this node cannot be NULL. */
redisAssert(x != NULL);
/* Check if score >= min. */
// 反过来,又要检查该节点的分值是否超出range的左边界
if (!zslValueGteMin(x->score,range)) return NULL;
return x;
}
/* Delete all the elements with score between min and max from the skiplist.
* Min and max are inclusive, so a score >= min || score <= max is deleted.
* Note that this function takes the reference to the hash table view of the
* sorted set, in order to remove the elements from the hash table too. */
/* 在跳跃表中删除所有分值在给定范围range内的节点。
注意range中指定的min和max包含在范围之内(即闭区间),所以边界情况score >= min或者score <= max的节点也会被删除。
另外,不仅跳跃表zsl中的满足要求的节点会被删除,在字典dict中相应的节点也会被删除(以维持zset的一致性)。*/
unsigned long zslDeleteRangeByScore(zskiplist *zsl, zrangespec *range, dict *dict) {
// update数组用来记录降层节点
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
unsigned long removed = 0;
int i;
x = zsl->header;
// 从前往后遍历,记录降层节点,方面以后修改指针
for (i = zsl->level-1; i >= 0; i--) {
while (x->level[i].forward && (range->minex ?
x->level[i].forward->score <= range->min :
x->level[i].forward->score < range->min))
x = x->level[i].forward;
update[i] = x;
}
/* Current node is the last with score < or <= min. */
// 定位到第一次中待删除的第一个节点
x = x->level[0].forward;
/* Delete nodes while in range. */
// 删除range指定范围内的所有节点
while (x &&
(range->maxex ? x->score < range->max : x->score <= range->max))
{
// 记录下一个节点的位置
zskiplistNode *next = x->level[0].forward;
// 删除节点
zslDeleteNode(zsl,x,update);
// 删除dict中相应的元素
dictDelete(dict,x->obj);
zslFreeNode(x);
// 记录删除节点个数
removed++;
// 指向下一个节点
x = next;
}
return removed;
}
/* 删除元素值在指定字典序范围的元素,同样也会在dict中删除相应元素。*/
unsigned long zslDeleteRangeByLex(zskiplist *zsl, zlexrangespec *range, dict *dict) {
// update数组用来记录降层节点
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
unsigned long removed = 0;
int i;
x = zsl->header;
// 从前往后遍历,记录降层节点
for (i = zsl->level-1; i >= 0; i--) {
while (x->level[i].forward &&
!zslLexValueGteMin(x->level[i].forward->obj,range))
x = x->level[i].forward;
update[i] = x;
}
/* Current node is the last with score < or <= min. */
// 移动到第一个待删除节点的位置
x = x->level[0].forward;
/* Delete nodes while in range. */
// 删除指定范围内的元素
while (x && zslLexValueLteMax(x->obj,range)) {
// 记录下一个节点位置
zskiplistNode *next = x->level[0].forward;
zslDeleteNode(zsl,x,update);
dictDelete(dict,x->obj);
zslFreeNode(x);
removed++;
// 继续处理下一个节点
x = next;
}
return removed;
}
/* Delete all the elements with rank between start and end from the skiplist.
* Start and end are inclusive. Note that start and end need to be 1-based */
/* 在跳跃表中删除给定排序范围的节点,注意两点:一是参数start和参数end是包含在内的,二是参数start和参数end都是
从1开始计数的。该函数最后返回被删除节点数量。*/
unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
// update数组用来记录降层节点
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
unsigned long traversed = 0, removed = 0;
int i;
x = zsl->header;
// 从前往后遍历跳跃表,定位到指定排位的起始位置的前置节点,并记录降层节点
for (i = zsl->level-1; i >= 0; i--) {
while (x->level[i].forward && (traversed + x->level[i].span) < start) {
traversed += x->level[i].span;
x = x->level[i].forward;
}
update[i] = x;
}
// 当前排位
traversed++;
// 指向排位起始的第一个节点
x = x->level[0].forward;
// 删除落在指定排序范围的所有节点
while (x && traversed <= end) {
// 记录下一个节点
zskiplistNode *next = x->level[0].forward;
// 从跳跃表中删除节点
zslDeleteNode(zsl,x,update);
// 从字典dict中删除节点
dictDelete(dict,x->obj);
zslFreeNode(x);
// 被删除元素个数加1
removed++;
// 排位计数加1
traversed++;
// 指向下一个节点
x = next;
}
return removed;
}
/* Find the rank for an element by both score and key.
* Returns 0 when the element cannot be found, rank otherwise.
* Note that the rank is 1-based due to the span of zsl->header to the
* first element. */
/* 返回指定元素在跳跃表中的排位,该元素由分值score和元素值对象o指定。
如果该元素不在跳跃表中返回0,否则返回相应排位。
注意到由于跳跃表的头结点header也包含在内并作为第1个元素(下标为0),排位rank是从1开始计算的。*/
unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
zskiplistNode *x;
unsigned long rank = 0;
int i;
x = zsl->header;
// 从前往后遍历跳远表,逐一对当前节点和目标节点进行比对。既要比对分值score也要比对节点的元素值
for (i = zsl->level-1; i >= 0; i--) {
while (x->level[i].forward &&
(x->level[i].forward->score < score ||
(x->level[i].forward->score == score &&
compareStringObjects(x->level[i].forward->obj,o) <= 0))) {
// 更新排位信息
rank += x->level[i].span;
x = x->level[i].forward;
}
/* x might be equal to zsl->header, so test if obj is non-NULL */
// x可能指向头结点,需要再次测试
if (x->obj && equalStringObjects(x->obj,o)) {
return rank;
}
}
return 0;
}
/* Finds an element by its rank. The rank argument needs to be 1-based. */
/* 返回指定排位上的节点,参数rank是从1开始计算的。*/
zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
zskiplistNode *x;
// 记录当前的排位信息
unsigned long traversed = 0;
int i;
x = zsl->header;
// 从前往后开始遍历,简答的查找过程,可以与链表查找第i个节点的操作进行类比
for (i = zsl->level-1; i >= 0; i--) {
while (x->level[i].forward && (traversed + x->level[i].span) <= rank)
{
traversed += x->level[i].span;
x = x->level[i].forward;
}
if (traversed == rank) {
return x;
}
}
return NULL;
}
/* Populate the rangespec according to the objects min and max. */
/* 从min何max对象中解析出一个min-max区间,并存入spec中。*/
static int zslParseRange(robj *min, robj *max, zrangespec *spec) {
char *eptr;
// 默认为闭区间
spec->minex = spec->maxex = 0;
/* Parse the min-max interval. If one of the values is prefixed
* by the "(" character, it's considered "open". For instance
* ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
* ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
/*
从命令行输入中解析min-max区间。如果一个输入参数以‘(’字符作为前缀,则认为是开区间的。
比如ZRANGEBYSCORE zset (1.5 (2.5,解析为区间(1.5, 2.5)
比如ZRANGEBYSCORE zset 1.5 2.5,解析为区间[1.5, 2.5]
*/
// 确定spec->min数值和开闭情况
if (min->encoding == REDIS_ENCODING_INT) {
// 如果是整型编码,直接确定边界
spec->min = (long)min->ptr;
} else {
// min对象为字符串编码,根据第一个字符确定开区间 or 闭区间
if (((char*)min->ptr)[0] == '(') {
// strtod将字符串解析为浮点数
spec->min = strtod((char*)min->ptr+1,&eptr);
if (eptr[0] != '\0' || isnan(spec->min)) return REDIS_ERR;
spec->minex = 1;
} else {
spec->min = strtod((char*)min->ptr,&eptr);
if (eptr[0] != '\0' || isnan(spec->min)) return REDIS_ERR;
}
}
// 确定spec->max数值和开闭情况
if (max->encoding == REDIS_ENCODING_INT) {
// 如果是整型编码,直接确定边界
spec->max = (long)max->ptr;
} else {
// max对象为字符串编码,根据第一个字符确定开区间 or 闭区间
if (((char*)max->ptr)[0] == '(') {
spec->max = strtod((char*)max->ptr+1,&eptr);
if (eptr[0] != '\0' || isnan(spec->max)) return REDIS_ERR;
spec->maxex = 1;
} else {
spec->max = strtod((char*)max->ptr,&eptr);
if (eptr[0] != '\0' || isnan(spec->max)) return REDIS_ERR;
}
}
return REDIS_OK;
}
/* ------------------------ Lexicographic ranges ---------------------------- */
/* ------------------------ 字典序范围 ---------------------------- */
/* Parse max or min argument of ZRANGEBYLEX.
* (foo means foo (open interval)
* [foo means foo (closed interval)
* - means the min string possible
* + means the max string possible
*
* If the string is valid the *dest pointer is set to the redis object
* that will be used for the comparision, and ex will be set to 0 or 1
* respectively if the item is exclusive or inclusive. REDIS_OK will be
* returned.
*
* If the string is not a valid range REDIS_ERR is returned, and the value
* of *dest and *ex is undefined. */
/* 该函数主要用于解析ZRANGEBYLEX命令的min参数或max参数。
(foo 表示开区间
[foo 表示闭区间
- 表示最小的字符串
+ 表示最大的字符串
如果输入字符串合法则将解析后的结构存放在dest中。
如果解析后的边界是闭区间,则ex被设置为0,如果是开区间,则ex被设置为1。
返回值为REDIS_OK表示解析成功
如果输入字符串不合法,则返回REDIS_ERR,此时dest和ex的值的undefined的。
!!!关于这个函数的作用大家可以联系ZRANGEBYLEX命令来理解!!!
*/
int zslParseLexRangeItem(robj *item, robj **dest, int *ex) {
char *c = item->ptr;
// 根据第一个字符即可做出判断
switch(c[0]) {
case '+':
if (c[1] != '\0') return REDIS_ERR;
*ex = 0;
// 边界值为shared.maxstring
*dest = shared.maxstring;
incrRefCount(shared.maxstring);
return REDIS_OK;
case '-':
if (c[1] != '\0') return REDIS_ERR;
*ex = 0;
// 边界值为shared.minstring
*dest = shared.minstring;
incrRefCount(shared.minstring);
return REDIS_OK;
case '(':
// 设置为开区间
*ex = 1;
// 获取边界值
*dest = createStringObject(c+1,sdslen(c)-1);
return REDIS_OK;
case '[':
// 设置为闭区间
*ex = 0;
// 获取边界值
*dest = createStringObject(c+1,sdslen(c)-1);
return REDIS_OK;
default:
return REDIS_ERR;
}
}
/* Populate the rangespec according to the objects min and max.
*
* Return REDIS_OK on success. On error REDIS_ERR is returned.
* When OK is returned the structure must be freed with zslFreeLexRange(),
* otherwise no release is needed. */
/* 将min和max指定的字符串进行解析,填入字典区间zlexrangespec中,操作成功返回REDIS_OK,否则返回REDIS_ERR。
注意,如果操作成功,则以后需要使用zslFreeLexRange来释放spec结构,否则并不一定需要释放资源。
该函数是zslParseLexRangeItem的封装,后者每次只能解析一个参数。
*/
static int zslParseLexRange(robj *min, robj *max, zlexrangespec *spec) {
/* The range can't be valid if objects are integer encoded.
* Every item must start with ( or [. */
// 由于每个参数只能是字符串编码的,如果是整型编码则无法解析
if (min->encoding == REDIS_ENCODING_INT ||
max->encoding == REDIS_ENCODING_INT) return REDIS_ERR;
spec->min = spec->max = NULL;
// 分别调用zslParseLexRangeItem来解析min参数和max参数
if (zslParseLexRangeItem(min, &spec->min, &spec->minex) == REDIS_ERR ||
zslParseLexRangeItem(max, &spec->max, &spec->maxex) == REDIS_ERR) {
if (spec->min) decrRefCount(spec->min);
if (spec->max) decrRefCount(spec->max);
return REDIS_ERR;
} else {
return REDIS_OK;
}
}
/* Free a lex range structure, must be called only after zelParseLexRange()
* populated the structure with success (REDIS_OK returned). */
/* 释放一个字典序区间结构,因为zlexrangespec存在两个robj对象。
zslParseLexRange调用成功后必须调用该函数来说释放资源。*/
void zslFreeLexRange(zlexrangespec *spec) {
decrRefCount(spec->min);
decrRefCount(spec->max);
}
/* This is just a wrapper to compareStringObjects() that is able to
* handle shared.minstring and shared.maxstring as the equivalent of
* -inf and +inf for strings */
/* 字典序字符串比较函数,实际上是在compareStringObjects函数封装的基础上增加了对
shared.minstring和shared.maxstring的处理。*/
int compareStringObjectsForLexRange(robj *a, robj *b) {
if (a == b) return 0; /* This makes sure that we handle inf,inf and
-inf,-inf ASAP. One special case less. */
if (a == shared.minstring || b == shared.maxstring) return -1;
if (a == shared.maxstring || b == shared.minstring) return 1;
return compareStringObjects(a,b);
}
/* 以字典序方式判断给定值value是否 > 或者 >= spec.min。 */
static int zslLexValueGteMin(robj *value, zlexrangespec *spec) {
return spec->minex ?
(compareStringObjectsForLexRange(value,spec->min) > 0) :
(compareStringObjectsForLexRange(value,spec->min) >= 0);
}
/* 以字典序方式判断给定值value是否 < 或者 <= spec.max。 */
static int zslLexValueLteMax(robj *value, zlexrangespec *spec) {
return spec->maxex ?
(compareStringObjectsForLexRange(value,spec->max) < 0) :
(compareStringObjectsForLexRange(value,spec->max) <= 0);
}
/* Returns if there is a part of the zset is in the lex range. */
/* 判断跳跃表中是否有一部分节点落在字典序区间内。
注意,比较的不是分值score,而是obj。 */
int zslIsInLexRange(zskiplist *zsl, zlexrangespec *range) {
zskiplistNode *x;
/* Test for ranges that will always be empty. */
// 判断字典序区间是否合法
if (compareStringObjectsForLexRange(range->min,range->max) > 1 ||
(compareStringObjects(range->min,range->max) == 0 &&
(range->minex || range->maxex)))
return 0;
x = zsl->tail;
if (x == NULL || !zslLexValueGteMin(x->obj,range))
return 0;
x = zsl->header->level[0].forward;
if (x == NULL || !zslLexValueLteMax(x->obj,range))
return 0;
return 1;
}
/* Find the first node that is contained in the specified lex range.
* Returns NULL when no element is contained in the range. */
/* 查找跳跃表中落在字典序区间范围的第一个节点,如果不存在这样的节点则返回NULL。*/
zskiplistNode *zslFirstInLexRange(zskiplist *zsl, zlexrangespec *range) {
zskiplistNode *x;
int i;
/* If everything is out of range, return early. */
// 如果跳跃表中没有节点落在指定字典序区间,则直接退出
if (!zslIsInLexRange(zsl,range)) return NULL;
x = zsl->header;
// 从前往后遍历跳跃表,查找满足要求的第一个节点
for (i = zsl->level-1; i >= 0; i--) {
/* Go forward while *OUT* of range. */
while (x->level[i].forward &&
!zslLexValueGteMin(x->level[i].forward->obj,range))
x = x->level[i].forward;
}
/* This is an inner range, so the next node cannot be NULL. */
// 移动到目标节点
x = x->level[0].forward;
redisAssert(x != NULL);
/* Check if score <= max. */
// 最后再次验证是否超出右边界
if (!zslLexValueLteMax(x->obj,range)) return NULL;
return x;
}
/* Find the last node that is contained in the specified range.
* Returns NULL when no element is contained in the range. */
/* 查找跳跃表中落在字典序区间范围的最后一个节点,如果不存在这样的节点则返回NULL。*/
zskiplistNode *zslLastInLexRange(zskiplist *zsl, zlexrangespec *range) {
zskiplistNode *x;
int i;
/* If everything is out of range, return early. */
// 如果跳跃表中没有节点落在指定字典序区间,则直接退出
if (!zslIsInLexRange(zsl,range)) return NULL;
x = zsl->header;
// 从前往后遍历跳跃表,查找满足要求的最后一个节点
for (i = zsl->level-1; i >= 0; i--) {
/* Go forward while *IN* range. */
while (x->level[i].forward &&
zslLexValueLteMax(x->level[i].forward->obj,range))
x = x->level[i].forward;
}
/* This is an inner range, so this node cannot be NULL. */
redisAssert(x != NULL);
/* Check if score >= min. */
// 最后验证是否超出左边界
if (!zslLexValueGteMin(x->obj,range)) return NULL;
return x;
}
/*-----------------------------------------------------------------------------
* Ziplist-backed sorted set API 以ziplis为底层结构的zset操作
*----------------------------------------------------------------------------*/
/****************************************************************************************
如果zset使用ziplist作为底层结构,则每个有序集元素以两个相邻的ziplist节点表示, 第一个节点保存元素值,
接下来的第二个元素保存元素的分值score。为了方便描述,我们分别将这两个节点称之为“元素值节点”和“分值节点”
*****************************************************************************************/
/* 获取sptr指针所指节点的分值score,实际上就是获取有序集合中某个元素的分值score域。 */
double zzlGetScore(unsigned char *sptr) {
unsigned char *vstr;
unsigned int vlen;
long long vlong;
char buf[128];
double score;
redisAssert(sptr != NULL);
// 调用ziplistGet获取节点的值,如果该节点保存的是字符串,则存放在vstr中,如果该节点保存的是整数,则
// 保存在vlong中
redisAssert(ziplistGet(sptr,&vstr,&vlen,&vlong));
if (vstr) {
memcpy(buf,vstr,vlen);
buf[vlen] = '\0';
// 将字符串转换为double
score = strtod(buf,NULL);
} else {
score = vlong;
}
return score;
}
/* Return a ziplist element as a Redis string object.
* This simple abstraction can be used to simplifies some code at the
* cost of some performance. */
/* 获取sptr指针所指节点的存放的数据,并以Redis对象robj的类型返回。
实际上就是获取有序集合中某个元素的元素值value域。*/
robj *ziplistGetObject(unsigned char *sptr) {
unsigned char *vstr;
unsigned int vlen;
long long vlong;
redisAssert(sptr != NULL);
// 调用ziplistGet获取节点的值,如果该节点保存的是字符串,则存放在vstr中,如果该节点保存的是整数,则
// 保存在vlong中
redisAssert(ziplistGet(sptr,&vstr,&vlen,&vlong));
// 更具不同类型创建Redis对象
if (vstr) {
return createStringObject((char*)vstr,vlen);
} else {
return createStringObjectFromLongLong(vlong);
}
}
/* Compare element in sorted set with given element. */
/* 将ziplist中eptr所指节点的元素与cstr字符串进行比较。既然是字符串比较,那比较结果可能是:
(1)、如果两个相同,返回0
(2)、如果eptr中的字符串 > cstr字符串,则返回一个正数
(3)、如果eptr中的字符串 < cstr字符串,则返回一个负数
*/
int zzlCompareElements(unsigned char *eptr, unsigned char *cstr, unsigned int clen) {
unsigned char *vstr;
unsigned int vlen;
long long vlong;
unsigned char vbuf[32];
int minlen, cmp;
// 调用ziplistGet获取节点的值,如果该节点保存的是字符串,则存放在vstr中,如果该节点保存的是整数,则
// 保存在vlong中
redisAssert(ziplistGet(eptr,&vstr,&vlen,&vlong));
if (vstr == NULL) {
/* Store string representation of long long in buf. */
// 如果eptr节点保存的是一个整型,则转换为字符串
vlen = ll2string((char*)vbuf,sizeof(vbuf),vlong);
vstr = vbuf;
}
minlen = (vlen < clen) ? vlen : clen;
// 使用memcmp进行字符串比较
cmp = memcmp(vstr,cstr,minlen);
if (cmp == 0) return vlen-clen;
return cmp;
}
/* 返回ziplist编码的有序集合中保存的元素个数,ziplist每两个节点看作有序集合中的一个元素。*/
unsigned int zzlLength(unsigned char *zl) {
return ziplistLen(zl)/2;
}
/* Move to next entry based on the values in eptr and sptr. Both are set to
* NULL when there is no next entry. */
/* ziplist编码的有序集合的迭代函数,eptr和sptr是相邻的两个节点,被看做是有序集合中的一个元素,其中
eptr指向有序集合当前元素的元素值节点,sptr指向相应的分值节点。移动eptr和sptr分别获得下一个元素的元素值节点和分值节点。
如果后面已经没有元素则返回NULL。*/
void zzlNext(unsigned char *zl, unsigned char **eptr, unsigned char **sptr) {
unsigned char *_eptr, *_sptr;
redisAssert(*eptr != NULL && *sptr != NULL);
// 获得sptr的下一个节点,即有序集合下一个元素的元素值节点
_eptr = ziplistNext(zl,*sptr);
if (_eptr != NULL) {
// 获得有序集合下一个元素的分值节点
_sptr = ziplistNext(zl,_eptr);
redisAssert(_sptr != NULL);
} else {
/* No next entry. */
_sptr = NULL;
}
*eptr = _eptr;
*sptr = _sptr;
}
/* Move to the previous entry based on the values in eptr and sptr. Both are
* set to NULL when there is no next entry. */
/* ziplist编码的有序集合的迭代函数,eptr和sptr是相邻的两个节点,被看做是有序集合中的一个元素,其中
eptr指向有序集合当前元素的元素值节点,sptr指向相应的分值节点。移动eptr和sptr分别获得前一个元素的元素值节点和分值节点。
如果前面已经没有元素则返回NULL。*/
void zzlPrev(unsigned char *zl, unsigned char **eptr, unsigned char **sptr) {
unsigned char *_eptr, *_sptr;
redisAssert(*eptr != NULL && *sptr != NULL);
// 获得eptr的前一个节点,即分值节点
_sptr = ziplistPrev(zl,*eptr);
if (_sptr != NULL) {
// 获得_sptr的前一个节点,即元素值节点
_eptr = ziplistPrev(zl,_sptr);
redisAssert(_eptr != NULL);
} else {
/* No previous entry. */
_eptr = NULL;
}
*eptr = _eptr;
*sptr = _sptr;
}
/* Returns if there is a part of the zset is in range. Should only be used
* internally by zzlFirstInRange and zzlLastInRange. */
/* 判断ziplist编码的有序集合是不是有一部分分值score落在range指定的范围内,如果有则返回1,否则返回0。
注意这是一个内部函数,供zzlFirstInRange和zzlLastInRange函数调用。*/
int zzlIsInRange(unsigned char *zl, zrangespec *range) {
unsigned char *p;
double score;
/* Test for ranges that will always be empty. */
// 检查range指定的区间是否为空区间
if (range->min > range->max ||
(range->min == range->max && (range->minex || range->maxex)))
return 0;
// ziplist中的分值是有序排列的,最后一个为最大的分值
p = ziplistIndex(zl,-1); /* Last score. */
if (p == NULL) return 0; /* Empty sorted set */
// 从节点中获取分值score
score = zzlGetScore(p);
if (!zslValueGteMin(score,range))
return 0;
// 获取最小的一个分值节点
p = ziplistIndex(zl,1); /* First score. */
redisAssert(p != NULL);
// 从节点中获取分值score
score = zzlGetScore(p);
if (!zslValueLteMax(score,range))
return 0;
return 1;
}
/* Find pointer to the first element contained in the specified range.
* Returns NULL when no element is contained in the range. */
/* 返回ziplist编码的有序集合中第一个分值落在range范围内的元素(即元素值节点指针),
如果不存在这样的节点则返回NULL。*/
unsigned char *zzlFirstInRange(unsigned char *zl, zrangespec *range) {
// eptr指向第一个元素(ziplist每两个相连的节点作为有序集合中的一个元素)
unsigned char *eptr = ziplistIndex(zl,0), *sptr;