-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy patht_zset.c
5333 lines (4609 loc) · 201 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.
*
* 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").
*
* Note that the SDS string representing the element is the same in both
* the hash table and skiplist in order to save memory. What we do in order
* to manage the shared SDS string more easily is to free the SDS string
* only in zslFreeNode(). The dictionary has no value free method set.
* So we should always remove an element from the dictionary, and later from
* the skiplist.
*
* 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. */
#include "server.h"
#include <math.h>
/*-----------------------------------------------------------------------------
* Skiplist implementation of the low level API
*----------------------------------------------------------------------------*/
/* 有序集合类型为 skiplist 时的 API 实现 */
/* 温馨提示:
* 1. 中文注释所提到的有序集合的 “成员” 是一个 [element,score] (即使英文注释写 element 也翻译成 “成员”),
* 元素单指 element ,分数单指 score 。
* 2. 跳表的前向指针(forward)不是我们经常写的双向链表中的 prev,而是 next,
* 后向指针(backward)才是双链表中的 prev,不要看着名字搞混了哦~ */
int zslLexValueGteMin(sds value, zlexrangespec *spec);
int zslLexValueLteMax(sds value, zlexrangespec *spec);
/* Create a skiplist node with the specified number of levels.
* The SDS string 'ele' is referenced by the node after the call. */
/* 创建一个具有指定层数的跳表节点, SDS字符串 'ele' 在调用后被节点引用 */
zskiplistNode *zslCreateNode(int level, double score, sds ele) {
zskiplistNode *zn =
zmalloc(sizeof(*zn)+level*sizeof(struct zskiplistLevel));
zn->score = score;
zn->ele = ele;
return zn;
}
/* Create a new skiplist. */
/* 创建新跳表 */
zskiplist *zslCreate(void) {
int j;
zskiplist *zsl;
zsl = zmalloc(sizeof(*zsl));
zsl->level = 1;
zsl->length = 0;
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;
}
zsl->header->backward = NULL;
zsl->tail = NULL;
return zsl;
}
/* Free the specified skiplist node. The referenced SDS string representation
* of the element is freed too, unless node->ele is set to NULL before calling
* this function. */
/* 释放指定的跳表节点。
* 成员的引用 SDS字符串 也会被释放,除非在调用此函数之前将 node->ele 设置为 NULL */
void zslFreeNode(zskiplistNode *node) {
sdsfree(node->ele);
zfree(node);
}
/* Free a whole skiplist. */
/* 释放整个跳表 */
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. */
/* 为我们将要创建的新跳表节点返回一个随机的 level(最高层数)。
* 这个函数的返回值介于 1 和 ZSKIPLIST_MAXLEVEL 之间(包括两者),
* 返回值有一个类似幂律的分布,越高的 level 返回可能性就越低。 */
int zslRandomLevel(void) {
/* 计算阈值 */
static const int threshold = ZSKIPLIST_P*RAND_MAX;
int level = 1;
/* 当随机数小于阈值时,level 继续增加 */
while (random() < threshold)
level += 1;
/* 返回 level,同时做不要让 level 大于最大层数的操作 */
return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
}
/* Insert a new node in the skiplist. Assumes the element does not already
* exist (up to the caller to enforce that). The skiplist takes ownership
* of the passed SDS string 'ele'. */
/* 在 skiplist 中插入一个新节点。假设要加入的成员不存在(由调用者决定是否执行)。
* skiplist 将拥有传递的 SDS字符串 'ele' 的所有权(即直接引用 ele 而非复制一个副本并引用该副本) */
zskiplistNode *zslInsert(zskiplist *zsl, double score, sds ele) {
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x; /* update 记录比插入元素 score 或字典序小的最近节点 */
unsigned long rank[ZSKIPLIST_MAXLEVEL]; /* 用于记录插入位置在每层中跨越了多少个节点 */
int i, level;
serverAssert(!isnan(score));
x = zsl->header;
/* 从最高层向下查找插入位置 */
for (i = zsl->level-1; i >= 0; i--) {
/* store rank that is crossed to reach the insert position */
/* rank 存储到达插入位置而跨越的节点数 */
rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
while (x->level[i].forward &&
(x->level[i].forward->score < score ||
(x->level[i].forward->score == score &&
sdscmp(x->level[i].forward->ele,ele) < 0)))
{
rank[i] += x->level[i].span;
x = x->level[i].forward;
}
update[i] = x;
}
/* we assume the element is not already inside, since we allow duplicated
* scores, reinserting the same element should never happen since the
* caller of zslInsert() should test in the hash table if the element is
* already inside or not. */
/* 我们假设成员不在内部,
* 我们允许重复的分数(score),但重新插入相同的成员应永远不会发生,
* 因为zslInsert()的调用方应测试成员是否已经在哈希表内部
* (zset 使用跳表结构时,用哈希表保存成员和分数的对应关系,而跳表用于根据分数查询数据) */
/* 获取随机最高层数 */
level = zslRandomLevel();
/* 随机获取的 level 比跳表原来的 level 大,则在比原来 level 高的层级上初始化 rank 和 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;
}
/* 将跳表的 level(最高层数) 替换为随机获取到的 level */
zsl->level = level;
}
/* 创建跳表节点 */
x = zslCreateNode(level,score,ele);
/* 插入新节点 */
for (i = 0; i < level; i++) {
x->level[i].forward = update[i]->level[i].forward;
update[i]->level[i].forward = x;
/* update span covered by update[i] as x is inserted here */
/* 更新 update[i] 所涵盖的跨度,因为有新节点(x)被插入了 */
/* 首先更新新节点的跨度 */
x->level[i].span = update[i]->level[i].span - (rank[0] - rank[i]);
/* 更新 update 的跨度 */
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++;
}
/* 设置新节点的后向指针 */
x->backward = (update[0] == zsl->header) ? NULL : update[0];
/* 设置新节点的下一个节点的后向指针,若下一个节点不存在,则将尾指针指向新节点 */
if (x->level[0].forward)
x->level[0].forward->backward = x;
else
zsl->tail = x;
/* 节点数计数增加 */
zsl->length++;
/* 返回新节点 */
return x;
}
/* Internal function used by zslDelete, zslDeleteRangeByScore and
* zslDeleteRangeByRank. */
/* 由 zslDelete、zslDeleteRangeByScore 和 zslDeleteRangeByRank 使用的内部实现函数,
* 用于删除跳表中的节点 */
void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
int i;
/* 更新 update[i] 的前向指针以及跨度 */
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(被删除节点) 的下一个节点的后向指针,如果下一个节点不存在,则将尾指针指向 x 的上一个节点 */
if (x->level[0].forward) {
x->level[0].forward->backward = x->backward;
} else {
zsl->tail = x->backward;
}
/* 若被删除节点拥有最高的层数,则需要将跳表的最高层数下调至当前剩余节点中的最高层 */
while(zsl->level > 1 && zsl->header->level[zsl->level-1].forward == NULL)
zsl->level--;
zsl->length--;
}
/* Delete an element with matching score/element from the skiplist.
* The function returns 1 if the node was found and deleted, otherwise
* 0 is returned.
*
* If 'node' is NULL the deleted node is freed by zslFreeNode(), otherwise
* it is not freed (but just unlinked) and *node is set to the node pointer,
* so that it is possible for the caller to reuse the node (including the
* referenced SDS string at node->ele). */
/* 从跳表中删除一个指定的成员(由输入参数的 score 和 ele 指定) 。
* 如果找到并删除了该节点,该函数返回1,否则返回0。
*
* 如果 'node' 是 NULL,被删除的节点将被 zslFreeNode() 释放,
* 否则它不会被释放(只是取消与跳表的链接),*node 被设置为指向所删除的节点,
* 这样调用者就有可能重新使用该节点(包括 node->ele 引用的 SDS字符串)。*/
int zslDelete(zskiplist *zsl, double score, sds ele, zskiplistNode **node) {
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
int i;
x = zsl->header;
/* 从最高层向下查找要删除的节点 */
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 &&
sdscmp(x->level[i].forward->ele,ele) < 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. */
/* 我们可能有多个具有相同分数的成员,我们所需要的是具有正确分数和元素的成员
* (比对元素(字符串)由sdscmp 比较函数完成,两元素相同返回0) */
x = x->level[0].forward;
if (x && score == x->score && sdscmp(x->ele,ele) == 0) {
/* 删除节点 */
zslDeleteNode(zsl, x, update);
/* 输入参数 node 不为空则释放被删除节点,否则令 *node 指向它 */
if (!node)
zslFreeNode(x);
else
*node = x;
return 1;
}
return 0; /* not found */
}
/* Update the score of an element inside the sorted set skiplist.
* Note that the element must exist and must match 'score'.
* This function does not update the score in the hash table side, the
* caller should take care of it.
*
* Note that this function attempts to just update the node, in case after
* the score update, the node would be exactly at the same position.
* Otherwise the skiplist is modified by removing and re-adding a new
* element, which is more costly.
*
* The function returns the updated element skiplist node pointer. */
/* 更新跳表中的一个成员的分数。
* 注意,该成员必须存在,并且必须与 'score' 相匹配。
* 这个函数不更新哈希表中的分数,而是由调用者负责。
*
* 这个函数试图只更新当前节点,在分数更新后,该节点能完全处在同一位置。
* 如果无法做到,跳表将通过删除和重新添加一个新的成员,这样做的开销代价更大。
*
* 该函数返回更新的成员的跳表节点指针。*/
zskiplistNode *zslUpdateScore(zskiplist *zsl, double curscore, sds ele, double newscore) {
zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
int i;
/* We need to seek to element to update to start: this is useful anyway,
* we'll have to update or remove it. */
/* 我们需要先找到成员,再开始执行更新操作 */
x = zsl->header;
/* 从最高层向下查找成员 */
for (i = zsl->level-1; i >= 0; i--) {
while (x->level[i].forward &&
(x->level[i].forward->score < curscore ||
(x->level[i].forward->score == curscore &&
sdscmp(x->level[i].forward->ele,ele) < 0)))
{
x = x->level[i].forward;
}
update[i] = x;
}
/* Jump to our element: note that this function assumes that the
* element with the matching score exists. */
/* 跳转到我们的成员:注意,这个断言假定具有与指定分数匹配的成员的存在 */
x = x->level[0].forward;
serverAssert(x && curscore == x->score && sdscmp(x->ele,ele) == 0);
/* If the node, after the score update, would be still exactly
* at the same position, we can just update the score without
* actually removing and re-inserting the element in the skiplist. */
/* 如果节点在分数更新后,仍然完全处于相同的位置(有序性不被破坏),
* 我们可以只更新分数,而不需要实际删除和重新插入该成员到跳表中。*/
if ((x->backward == NULL || x->backward->score < newscore) &&
(x->level[0].forward == NULL || x->level[0].forward->score > newscore))
{
x->score = newscore;
return x;
}
/* No way to reuse the old node: we need to remove and insert a new
* one at a different place. */
/* 没有办法重新使用旧的节点(有序性被破坏):我们需要移除旧节点并在不同的位置插入一个新的节点。*/
zslDeleteNode(zsl, x, update);
zskiplistNode *newnode = zslInsert(zsl,newscore,x->ele);
/* We reused the old node x->ele SDS string, free the node now
* since zslInsert created a new one. */
/* 我们重新使用了旧节点的 x->ele(因为新节点直接引用了 x->ele ),
* 现在释放这个节点,因为我们已经用 zslInsert 创建了一个新的节点 */
x->ele = NULL;
zslFreeNode(x);
return newnode;
}
/* 根据最小值是否具有排他性,检查 value 是否合法 */
int zslValueGteMin(double value, zrangespec *spec) {
return spec->minex ? (value > spec->min) : (value >= spec->min);
}
/* 根据最大值是否具有排他性,检查 value 是否合法 */
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. */
/* 检查 zset 中是否存在输入的范围。
* 如果 zset 的某一部分在范围内,则返回1,否则返回 0 */
int zslIsInRange(zskiplist *zsl, zrangespec *range) {
zskiplistNode *x;
/* Test for ranges that will always be empty. */
/* 测试永远为空的范围 */
if (range->min > range->max ||
(range->min == range->max && (range->minex || range->maxex)))
return 0;
x = zsl->tail; /* 令 x 跳到尾部(分数最大的成员) */
if (x == NULL || !zslValueGteMin(x->score,range))
return 0;
x = zsl->header->level[0].forward; /* 令 x 跳到头部(分数最大的成员) */
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. */
/* 寻找包含在指定范围内的第一个节点。如果没有成员包含在该范围内,则返回 NULL。*/
zskiplistNode *zslFirstInRange(zskiplist *zsl, zrangespec *range) {
zskiplistNode *x;
int i;
/* If everything is out of range, return early. */
/* 如果 zset 内不存在输入的范围,则提前返回 */
if (!zslIsInRange(zsl,range)) return NULL;
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
/* Go forward while *OUT* of range. */
/* 从跳表头部(分数最小的一端)开始寻找,直到 x 下一个节点的分数大于范围最小值时终止 */
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. */
/* 输入的范围是 zset 的内部范围,所以下一个节点不可能是 NULL。
* x 的下一个节点即是该内部范围的第一个元素 */
x = x->level[0].forward;
serverAssert(x != NULL);
/* Check if score <= max. */
/* 检查 score 是否小于范围的最大值 */
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. */
/* 寻找包含在指定范围内的最后一个节点。如果没有成员包含在该范围内,则返回 NULL */
zskiplistNode *zslLastInRange(zskiplist *zsl, zrangespec *range) {
zskiplistNode *x;
int i;
/* If everything is out of range, return early. */
/* 如果 zset 内不存在输入的范围,则提前返回 */
if (!zslIsInRange(zsl,range)) return NULL;
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
/* Go forward while *IN* range. */
/* 从跳表头部(分数最小的一端)开始寻找,直到 x 下一个节点的分数大于范围最大值时终止 */
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. */
/* 输入的范围是 zset 的内部范围,所以当前节点不可能是 NULL。
* 当前节点即是该内部范围的最后一个元素 */
serverAssert(x != NULL);
/* Check if score >= min. */
/* 检查 score 是否大于范围的最小值 */
if (!zslValueGteMin(x->score,range)) return NULL;
return x;
}
/* Delete all the elements with score between min and max from the skiplist.
* Both min and max can be inclusive or exclusive (see range->minex and
* range->maxex). When inclusive 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. */
/* 从跳表中删除所有分数在 min 和 max 之间的成员。
* min 和 max 都可以是包容的或排他的(见 range->minex 和 range->maxex)。
* 例如:当包含时,满足 score >= min && score <= max 的成员被删除。
* 请注意,这个函数需要对哈希表视图进行引用,以便也从哈希表中删除成员 */
unsigned long zslDeleteRangeByScore(zskiplist *zsl, zrangespec *range, dict *dict) {
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 &&
!zslValueGteMin(x->level[i].forward->score, range))
x = x->level[i].forward;
update[i] = x;
}
/* Current node is the last with score < or <= min. */
/* 当前节点是满足 score < min 或 score <= min 的最后一个节点。
* 我们这里令 x 指向下一个节点,即此时 x 是范围内的分数最小的节点 */
x = x->level[0].forward;
/* Delete nodes while in range. */
/* 将范围内的成员遍历删除 */
while (x && zslValueLteMax(x->score, range)) {
zskiplistNode *next = x->level[0].forward;
zslDeleteNode(zsl,x,update);
dictDelete(dict,x->ele); /* 将成员也从哈希表中删除 */
zslFreeNode(x); /* 在这里实际释放被删除的跳表节点 */
removed++; /* 删除成员的计数增加 */
x = next;
}
return removed;
}
/* 删除指定字典序范围内的成员。
* zrangebylex 命令使用提示:使用该命令时需要有序集合中所有成员的分数相等,
* 否则结果不准确!因为我们并不判断分数大小,只判断字典序大小 */
unsigned long zslDeleteRangeByLex(zskiplist *zsl, zlexrangespec *range, dict *dict) {
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->ele,range))
x = x->level[i].forward;
update[i] = x;
}
/* Current node is the last with score < or <= min. */
/* 当前节点是满足 lexicographic(字典序) < min 或 lexicographic <= min 的最后一个节点。
* 我们这里令 x 指向下一个节点,即此时 x 是范围内的分数最小的节点 */
x = x->level[0].forward;
/* Delete nodes while in range. */
/* 将范围内的成员遍历删除 */
while (x && zslLexValueLteMax(x->ele,range)) {
zskiplistNode *next = x->level[0].forward;
zslDeleteNode(zsl,x,update);
dictDelete(dict,x->ele); /* 将成员也从哈希表中删除 */
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 */
/* 从跳表中删除所有 rank(排位)在 start 和 end 之间的成员。
* 被删除的成员会包括 start 和 end 在内。
* 注意,start 和 end 是以 1 为第一个成员的 rank */
unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
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++; /* 记录当前成员的 rank */
/* 我们这里令 x 指向下一个节点,此时 x 是第 start 个节点 */
x = x->level[0].forward;
/* 遍历并删除第 start 个 到第 end 个成员 */
while (x && traversed <= end) {
zskiplistNode *next = x->level[0].forward;
zslDeleteNode(zsl,x,update);
dictDelete(dict,x->ele);
zslFreeNode(x);
removed++;
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 和 key 找到一个成员的 rank(排位)。
* 当找不到成员时返回0,否则返回 rank。
* 注意,rank 是从 1 开始的(而非以0代表第一个成员)
* 这是由于 rank 的计数方式为 rank += x->level[i].span,
* 而 zsl->header 到第一个成员的 span 为 1,所以第一个元素的 rank 为 1 */
unsigned long zslGetRank(zskiplist *zsl, double score, sds ele) {
zskiplistNode *x;
unsigned long rank = 0;
int i;
x = zsl->header;
/* 从最高层向下查找成员 */
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 &&
sdscmp(x->level[i].forward->ele,ele) <= 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 可能等于 zsl->header,所以测试 x->ele 是否为非 NULL */
if (x->ele && x->score == score && sdscmp(x->ele,ele) == 0) {
return rank;
}
}
return 0;
}
/* Finds an element by its rank. The rank argument needs to be 1-based. */
/* 根据一个成员的 rank 来查找到该成员。rank 参数是需要基于1的(原因可以看上面函数的注解) */
zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
zskiplistNode *x;
unsigned long traversed = 0;
int i;
x = zsl->header;
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 来填充 rangespec。*/
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 */
/* 解析最小-最大区间。如果其中一个值的前缀是"("字符,它就被认为是 "开区间"。
* 例如:
* ZRANGEBYSCORE zset (1.5 (2.5 将等于 1.5 < x < 2.5
* ZRANGEBYSCORE zset 1.5 2.5 将等于 1.5 <= x <= 2.5 */
if (min->encoding == OBJ_ENCODING_INT) {
spec->min = (long)min->ptr;
} else {
if (((char*)min->ptr)[0] == '(') {
spec->min = strtod((char*)min->ptr+1,&eptr);
if (eptr[0] != '\0' || isnan(spec->min)) return C_ERR;
spec->minex = 1;
} else {
spec->min = strtod((char*)min->ptr,&eptr);
if (eptr[0] != '\0' || isnan(spec->min)) return C_ERR;
}
}
if (max->encoding == OBJ_ENCODING_INT) {
spec->max = (long)max->ptr;
} else {
if (((char*)max->ptr)[0] == '(') {
spec->max = strtod((char*)max->ptr+1,&eptr);
if (eptr[0] != '\0' || isnan(spec->max)) return C_ERR;
spec->maxex = 1;
} else {
spec->max = strtod((char*)max->ptr,&eptr);
if (eptr[0] != '\0' || isnan(spec->max)) return C_ERR;
}
}
return C_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 comparison, and ex will be set to 0 or 1
* respectively if the item is exclusive or inclusive. C_OK will be
* returned.
*
* If the string is not a valid range C_ERR is returned, and the value
* of *dest and *ex is undefined. */
/* 解析 ZRANGEBYLEX 的最大或最小参数。
* (foo 表示 foo (开放区间)
* [foo 表示 foo (封闭区间)
* - 表示可能的最小字符串
* + 表示可能的最大字符串
*
* 如果字符串有效,*dest 指针将被设置为将用于比较的 redis对象,
* 根据 item 是排他性还是包容性,ex 将被分别设置为 0 或 1,最后 C_OK 将被返回。
*
* 如果字符串不是一个有效的范围,将返回 C_ERR,并且 *dest 和 *ex 的值是未被定义的。*/
int zslParseLexRangeItem(robj *item, sds *dest, int *ex) {
char *c = item->ptr;
switch(c[0]) {
case '+':
if (c[1] != '\0') return C_ERR;
*ex = 1;
*dest = shared.maxstring;
return C_OK;
case '-':
if (c[1] != '\0') return C_ERR;
*ex = 1;
*dest = shared.minstring;
return C_OK;
case '(':
*ex = 1;
*dest = sdsnewlen(c+1,sdslen(c)-1);
return C_OK;
case '[':
*ex = 0;
*dest = sdsnewlen(c+1,sdslen(c)-1);
return C_OK;
default:
return C_ERR;
}
}
/* Free a lex range structure, must be called only after zslParseLexRange()
* populated the structure with success (C_OK returned). */
/* 释放一个 zlexrangespec 结构,必须在 zslParseLexRange() 成功填充该结构(返回 C_OK)后才能调用 */
void zslFreeLexRange(zlexrangespec *spec) {
if (spec->min != shared.minstring &&
spec->min != shared.maxstring) sdsfree(spec->min);
if (spec->max != shared.minstring &&
spec->max != shared.maxstring) sdsfree(spec->max);
}
/* Populate the lex rangespec according to the objects min and max.
*
* Return C_OK on success. On error C_ERR is returned.
* When OK is returned the structure must be freed with zslFreeLexRange(),
* otherwise no release is needed. */
/* 根据对象 min 和 max 来填充 zlexrangespec。
*
* 成功时返回 C_OK,错误时返回 C_ERR。
* 当返回 OK 时,该结构必须用 zslFreeLexRange() 释放。
* 否则不需要释放。*/
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 [. */
/* 如果对象是整数编码的,范围无效。
* min 和 max 都必须以( 或 [ 做前缀 */
if (min->encoding == OBJ_ENCODING_INT ||
max->encoding == OBJ_ENCODING_INT) return C_ERR;
spec->min = spec->max = NULL;
if (zslParseLexRangeItem(min, &spec->min, &spec->minex) == C_ERR ||
zslParseLexRangeItem(max, &spec->max, &spec->maxex) == C_ERR) {
zslFreeLexRange(spec);
return C_ERR;
} else {
return C_OK;
}
}
/* This is just a wrapper to sdscmp() that is able to
* handle shared.minstring and shared.maxstring as the equivalent of
* -inf and +inf for strings */
/* 这只是 sdscmp() 的一个封装函数,
* 它能够处理 shared.minstring 和 shared.maxstring,相当于字符串的 -inf 和 +inf */
int sdscmplex(sds a, sds b) {
if (a == b) return 0;
if (a == shared.minstring || b == shared.maxstring) return -1;
if (a == shared.maxstring || b == shared.minstring) return 1;
return sdscmp(a,b);
}
/* 根据(字典序)最小值是否具有排他性,检查 value 是否合法 */
int zslLexValueGteMin(sds value, zlexrangespec *spec) {
return spec->minex ?
(sdscmplex(value,spec->min) > 0) :
(sdscmplex(value,spec->min) >= 0);
}
/* 根据(字典序)最大值是否具有排他性,检查 value 是否合法 */
int zslLexValueLteMax(sds value, zlexrangespec *spec) {
return spec->maxex ?
(sdscmplex(value,spec->max) < 0) :
(sdscmplex(value,spec->max) <= 0);
}
/* Returns if there is a part of the zset is in the lex range. */
/* 如果 zset 的某一部分在范围内,则返回1,否则返回0 */
int zslIsInLexRange(zskiplist *zsl, zlexrangespec *range) {
zskiplistNode *x;
/* Test for ranges that will always be empty. */
/* 测试永远为空的情况 */
int cmp = sdscmplex(range->min,range->max);
if (cmp > 0 || (cmp == 0 && (range->minex || range->maxex)))
return 0;
x = zsl->tail;
if (x == NULL || !zslLexValueGteMin(x->ele,range))
return 0;
x = zsl->header->level[0].forward;
if (x == NULL || !zslLexValueLteMax(x->ele,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. */
/* 如果 zset 内不存在该范围,则提前返回。*/
if (!zslIsInLexRange(zsl,range)) return NULL;
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
/* Go forward while *OUT* of range. */
/* 从跳表头部(字典序最小的一端)开始寻找,直到 x 下一个节点的字典序大于范围最小值时终止 */
while (x->level[i].forward &&
!zslLexValueGteMin(x->level[i].forward->ele,range))
x = x->level[i].forward;
}
/* This is an inner range, so the next node cannot be NULL. */
/* 我们令 x 指向下一个节点,下一个节点即为范围内的第一个节点 */
x = x->level[0].forward;
serverAssert(x != NULL);
/* Check if score <= max. */
/* 检查字典序是否小于等于范围最大值 */
if (!zslLexValueLteMax(x->ele,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. */
/* 如果 zset 内不存在该范围,则提前返回。*/
if (!zslIsInLexRange(zsl,range)) return NULL;
x = zsl->header;
for (i = zsl->level-1; i >= 0; i--) {
/* Go forward while *IN* range. */
/* 从跳表头部(字典序最小的一端)开始寻找,直到 x 下一个节点的字典序大于范围最大值时终止 */
while (x->level[i].forward &&
zslLexValueLteMax(x->level[i].forward->ele,range))
x = x->level[i].forward;
}
/* This is an inner range, so this node cannot be NULL. */
/* 当前节点为范围内的最后一个节点,且范围是属于 zset 内的,所以当前节点不可能是 NULL */
serverAssert(x != NULL);
/* Check if score >= min. */
/* 检查字典序是否小于等于范围最大值 */
if (!zslLexValueGteMin(x->ele,range)) return NULL;
return x;
}
/*-----------------------------------------------------------------------------
* Listpack-backed sorted set API
*----------------------------------------------------------------------------*/
/* 有序集合类型为 listpack 时的 API 实现 */
/* 字符串转 double */
double zzlStrtod(unsigned char *vstr, unsigned int vlen) {
char buf[128];
if (vlen > sizeof(buf) - 1)
vlen = sizeof(buf) - 1;
memcpy(buf,vstr,vlen);
buf[vlen] = '\0';
return strtod(buf,NULL);
}
/* 从 listpack 中获取分数(score) */
double zzlGetScore(unsigned char *sptr) {
unsigned char *vstr;
unsigned int vlen;
long long vlong;
double score;
serverAssert(sptr != NULL);
vstr = lpGetValue(sptr,&vlen,&vlong); /* 获取分数 */
/* 如果 vstr 存在,则分数是字符串编码,*/
if (vstr) {
score = zzlStrtod(vstr,vlen); /* 将字符串转 double */
/* vstr 为 NULL,则分数是整数编码,保存在 vlong 中 */
} else {
score = vlong;
}
return score;
}
/* Return a listpack element as an SDS string. */
/* 将一个 listpack 中的元素作为 SDS字符串 返回,注意返回的是一个副本 */
sds lpGetObject(unsigned char *sptr) {
unsigned char *vstr;
unsigned int vlen;
long long vlong;
serverAssert(sptr != NULL);
vstr = lpGetValue(sptr,&vlen,&vlong);
if (vstr) {
return sdsnewlen((char*)vstr,vlen);
} else {
return sdsfromlonglong(vlong);
}
}
/* Compare element in sorted set with given element. */
/* 将有序集合中的元素与给定的元素进行字典序比较
* 第一个元素(eptr) = 第二个元素(cstr) 返回0,
* 第一个元素(eptr) > 第二个元素(cstr) 返回正数,
* 第一个元素(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;