xref: /redis-3.2.3/src/intset.c (revision f3fd58eb)
1 /*
2  * Copyright (c) 2009-2012, Pieter Noordhuis <pcnoordhuis at gmail dot com>
3  * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  *   * Redistributions of source code must retain the above copyright notice,
10  *     this list of conditions and the following disclaimer.
11  *   * Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  *   * Neither the name of Redis nor the names of its contributors may be used
15  *     to endorse or promote products derived from this software without
16  *     specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include "intset.h"
35 #include "zmalloc.h"
36 #include "endianconv.h"
37 
38 /* Note that these encodings are ordered, so:
39  * INTSET_ENC_INT16 < INTSET_ENC_INT32 < INTSET_ENC_INT64. */
40 #define INTSET_ENC_INT16 (sizeof(int16_t))
41 #define INTSET_ENC_INT32 (sizeof(int32_t))
42 #define INTSET_ENC_INT64 (sizeof(int64_t))
43 
44 /* Return the required encoding for the provided value. */
45 static uint8_t _intsetValueEncoding(int64_t v) {
46     if (v < INT32_MIN || v > INT32_MAX)
47         return INTSET_ENC_INT64;
48     else if (v < INT16_MIN || v > INT16_MAX)
49         return INTSET_ENC_INT32;
50     else
51         return INTSET_ENC_INT16;
52 }
53 
54 /* Return the value at pos, given an encoding. */
55 static int64_t _intsetGetEncoded(intset *is, int pos, uint8_t enc) {
56     int64_t v64;
57     int32_t v32;
58     int16_t v16;
59 
60     if (enc == INTSET_ENC_INT64) {
61         memcpy(&v64,((int64_t*)is->contents)+pos,sizeof(v64));
62         memrev64ifbe(&v64);
63         return v64;
64     } else if (enc == INTSET_ENC_INT32) {
65         memcpy(&v32,((int32_t*)is->contents)+pos,sizeof(v32));
66         memrev32ifbe(&v32);
67         return v32;
68     } else {
69         memcpy(&v16,((int16_t*)is->contents)+pos,sizeof(v16));
70         memrev16ifbe(&v16);
71         return v16;
72     }
73 }
74 
75 /* Return the value at pos, using the configured encoding. */
76 static int64_t _intsetGet(intset *is, int pos) {
77     return _intsetGetEncoded(is,pos,intrev32ifbe(is->encoding));
78 }
79 
80 /* Set the value at pos, using the configured encoding. */
81 static void _intsetSet(intset *is, int pos, int64_t value) {
82     uint32_t encoding = intrev32ifbe(is->encoding);
83 
84     if (encoding == INTSET_ENC_INT64) {
85         ((int64_t*)is->contents)[pos] = value;
86         memrev64ifbe(((int64_t*)is->contents)+pos);
87     } else if (encoding == INTSET_ENC_INT32) {
88         ((int32_t*)is->contents)[pos] = value;
89         memrev32ifbe(((int32_t*)is->contents)+pos);
90     } else {
91         ((int16_t*)is->contents)[pos] = value;
92         memrev16ifbe(((int16_t*)is->contents)+pos);
93     }
94 }
95 
96 /* Create an empty intset. */
97 intset *intsetNew(void) {
98     intset *is = zmalloc(sizeof(intset));
99     is->encoding = intrev32ifbe(INTSET_ENC_INT16);
100     is->length = 0;
101     return is;
102 }
103 
104 /* Resize the intset */
105 static intset *intsetResize(intset *is, uint32_t len) {
106     uint32_t size = len*intrev32ifbe(is->encoding);
107     is = zrealloc(is,sizeof(intset)+size);
108     return is;
109 }
110 
111 /* Search for the position of "value". Return 1 when the value was found and
112  * sets "pos" to the position of the value within the intset. Return 0 when
113  * the value is not present in the intset and sets "pos" to the position
114  * where "value" can be inserted. */
115 static uint8_t intsetSearch(intset *is, int64_t value, uint32_t *pos) {
116     int min = 0, max = intrev32ifbe(is->length)-1, mid = -1;
117     int64_t cur = -1;
118 
119     /* The value can never be found when the set is empty */
120     if (intrev32ifbe(is->length) == 0) {
121         if (pos) *pos = 0;
122         return 0;
123     } else {
124         /* Check for the case where we know we cannot find the value,
125          * but do know the insert position. */
126         if (value > _intsetGet(is,intrev32ifbe(is->length)-1)) {
127             if (pos) *pos = intrev32ifbe(is->length);
128             return 0;
129         } else if (value < _intsetGet(is,0)) {
130             if (pos) *pos = 0;
131             return 0;
132         }
133     }
134 
135     while(max >= min) {
136         mid = ((unsigned int)min + (unsigned int)max) >> 1;
137         cur = _intsetGet(is,mid);
138         if (value > cur) {
139             min = mid+1;
140         } else if (value < cur) {
141             max = mid-1;
142         } else {
143             break;
144         }
145     }
146 
147     if (value == cur) {
148         if (pos) *pos = mid;
149         return 1;
150     } else {
151         if (pos) *pos = min;
152         return 0;
153     }
154 }
155 
156 /* Upgrades the intset to a larger encoding and inserts the given integer. */
157 static intset *intsetUpgradeAndAdd(intset *is, int64_t value) {
158     uint8_t curenc = intrev32ifbe(is->encoding);
159     uint8_t newenc = _intsetValueEncoding(value);
160     int length = intrev32ifbe(is->length);
161     int prepend = value < 0 ? 1 : 0;
162 
163     /* First set new encoding and resize */
164     is->encoding = intrev32ifbe(newenc);
165     is = intsetResize(is,intrev32ifbe(is->length)+1);
166 
167     /* Upgrade back-to-front so we don't overwrite values.
168      * Note that the "prepend" variable is used to make sure we have an empty
169      * space at either the beginning or the end of the intset. */
170     while(length--)
171         _intsetSet(is,length+prepend,_intsetGetEncoded(is,length,curenc));
172 
173     /* Set the value at the beginning or the end. */
174     if (prepend)
175         _intsetSet(is,0,value);
176     else
177         _intsetSet(is,intrev32ifbe(is->length),value);
178     is->length = intrev32ifbe(intrev32ifbe(is->length)+1);
179     return is;
180 }
181 
182 static void intsetMoveTail(intset *is, uint32_t from, uint32_t to) {
183     void *src, *dst;
184     uint32_t bytes = intrev32ifbe(is->length)-from;
185     uint32_t encoding = intrev32ifbe(is->encoding);
186 
187     if (encoding == INTSET_ENC_INT64) {
188         src = (int64_t*)is->contents+from;
189         dst = (int64_t*)is->contents+to;
190         bytes *= sizeof(int64_t);
191     } else if (encoding == INTSET_ENC_INT32) {
192         src = (int32_t*)is->contents+from;
193         dst = (int32_t*)is->contents+to;
194         bytes *= sizeof(int32_t);
195     } else {
196         src = (int16_t*)is->contents+from;
197         dst = (int16_t*)is->contents+to;
198         bytes *= sizeof(int16_t);
199     }
200     memmove(dst,src,bytes);
201 }
202 
203 /* Insert an integer in the intset */
204 intset *intsetAdd(intset *is, int64_t value, uint8_t *success) {
205     uint8_t valenc = _intsetValueEncoding(value);
206     uint32_t pos;
207     if (success) *success = 1;
208 
209     /* Upgrade encoding if necessary. If we need to upgrade, we know that
210      * this value should be either appended (if > 0) or prepended (if < 0),
211      * because it lies outside the range of existing values. */
212     if (valenc > intrev32ifbe(is->encoding)) {
213         /* This always succeeds, so we don't need to curry *success. */
214         return intsetUpgradeAndAdd(is,value);
215     } else {
216         /* Abort if the value is already present in the set.
217          * This call will populate "pos" with the right position to insert
218          * the value when it cannot be found. */
219         if (intsetSearch(is,value,&pos)) {
220             if (success) *success = 0;
221             return is;
222         }
223 
224         is = intsetResize(is,intrev32ifbe(is->length)+1);
225         if (pos < intrev32ifbe(is->length)) intsetMoveTail(is,pos,pos+1);
226     }
227 
228     _intsetSet(is,pos,value);
229     is->length = intrev32ifbe(intrev32ifbe(is->length)+1);
230     return is;
231 }
232 
233 /* Delete integer from intset */
234 intset *intsetRemove(intset *is, int64_t value, int *success) {
235     uint8_t valenc = _intsetValueEncoding(value);
236     uint32_t pos;
237     if (success) *success = 0;
238 
239     if (valenc <= intrev32ifbe(is->encoding) && intsetSearch(is,value,&pos)) {
240         uint32_t len = intrev32ifbe(is->length);
241 
242         /* We know we can delete */
243         if (success) *success = 1;
244 
245         /* Overwrite value with tail and update length */
246         if (pos < (len-1)) intsetMoveTail(is,pos+1,pos);
247         is = intsetResize(is,len-1);
248         is->length = intrev32ifbe(len-1);
249     }
250     return is;
251 }
252 
253 /* Determine whether a value belongs to this set */
254 uint8_t intsetFind(intset *is, int64_t value) {
255     uint8_t valenc = _intsetValueEncoding(value);
256     return valenc <= intrev32ifbe(is->encoding) && intsetSearch(is,value,NULL);
257 }
258 
259 /* Return random member */
260 int64_t intsetRandom(intset *is) {
261     return _intsetGet(is,rand()%intrev32ifbe(is->length));
262 }
263 
264 /* How many times bigger should the set length be compared to the requested
265  * count of members for us to use the Floyd algorithm instead of
266  * the Knuth algorithm */
267 #define RANDOMMEMBERS_ALGORITHM_SELECTION_RATIO (2)
268 
269 /* Copies 'count' random members from the set into the 'values' array.
270  * 'values' must be an array of int64_t values, of length 'count'.
271  * Returns the amount of items returned. If this amount is less than 'count',
272  * then the remaining 'values' are left uninitialized. */
273 int intsetRandomMembers(intset *is, int64_t* values, int count) {
274 
275     /* We don't check that is and values are non-NULL - the caller must
276      * play nice. */
277 
278     int length = intsetLen(is);
279 
280     if (count > length) {
281         /* Return everything in the set */
282         count = length;
283     }
284 
285     /* Choose between the Knuth shuffle algorithm, O(1) space, O(length) time,
286      * and the Floyd algorithm, O(length) space, O(count) time. */
287     if ((RANDOMMEMBERS_ALGORITHM_SELECTION_RATIO * count) > length) {
288 
289         /* If the count of members requested is almost the length of the set,
290          * use the Knuth shuffle algorithm, O(1) space, O(length) time. */
291 
292         /* First, fill the values array with unique random indexes inside
293          * the set. */
294         int in, im, rn, rm;
295         im = 0;
296         for (in = 0; in < length && im < count; in++) {
297 
298             rn = length - in;
299             rm = count - im;
300             if (rand() % rn < rm) {
301                 values[im++] = in;
302             }
303         }
304 
305     } else {
306 
307         /* If the length is considerably more than the count of members
308          * requested, use Robert Floyd's algorithm, O(length) space,
309          * O(count) time.
310          * Based on Jon Bentley's Programming Pearls */
311 
312         int64_t *is_used = zcalloc(sizeof(int64_t) * length);
313         int in, im, r;
314 
315         r = 0;
316         im = 0;
317 
318         for (in = length - count; in < length && im < count; in++) {
319 
320             /* Generate a random number r */
321             r = rand() % (in + 1);
322 
323             /* Do we already have the value in r? */
324             if (is_used[r]) {
325                 /* Use in instead of the generated number */
326                 r = in;
327             }
328 
329             values[im++] = r ;
330 
331             /* Mark it as used */
332             is_used[r] = 1;
333         }
334 
335         zfree(is_used);
336     }
337 
338     /* Replace each random index with the value stored there in the intset */
339     uint8_t encoding = intrev32ifbe(is->encoding);
340     for (int currentValue = 0; currentValue < count; currentValue++) {
341         values[currentValue] =
342             _intsetGetEncoded(is, values[currentValue], encoding);
343     }
344 
345     return count;
346 }
347 
348 /* Sets the value to the value at the given position. When this position is
349  * out of range the function returns 0, when in range it returns 1. */
350 uint8_t intsetGet(intset *is, uint32_t pos, int64_t *value) {
351     if (pos < intrev32ifbe(is->length)) {
352         *value = _intsetGet(is,pos);
353         return 1;
354     }
355     return 0;
356 }
357 
358 /* Return intset length */
359 uint32_t intsetLen(intset *is) {
360     return intrev32ifbe(is->length);
361 }
362 
363 /* Return intset blob size in bytes. */
364 size_t intsetBlobLen(intset *is) {
365     return sizeof(intset)+intrev32ifbe(is->length)*intrev32ifbe(is->encoding);
366 }
367 
368 #ifdef REDIS_TEST
369 #include <sys/time.h>
370 #include <time.h>
371 
372 #if 0
373 static void intsetRepr(intset *is) {
374     for (uint32_t i = 0; i < intrev32ifbe(is->length); i++) {
375         printf("%lld\n", (uint64_t)_intsetGet(is,i));
376     }
377     printf("\n");
378 }
379 
380 static void error(char *err) {
381     printf("%s\n", err);
382     exit(1);
383 }
384 #endif
385 
386 static void ok(void) {
387     printf("OK\n");
388 }
389 
390 static long long usec(void) {
391     struct timeval tv;
392     gettimeofday(&tv,NULL);
393     return (((long long)tv.tv_sec)*1000000)+tv.tv_usec;
394 }
395 
396 #define assert(_e) ((_e)?(void)0:(_assert(#_e,__FILE__,__LINE__),exit(1)))
397 static void _assert(char *estr, char *file, int line) {
398     printf("\n\n=== ASSERTION FAILED ===\n");
399     printf("==> %s:%d '%s' is not true\n",file,line,estr);
400 }
401 
402 static intset *createSet(int bits, int size) {
403     uint64_t mask = (1<<bits)-1;
404     uint64_t value;
405     intset *is = intsetNew();
406 
407     for (int i = 0; i < size; i++) {
408         if (bits > 32) {
409             value = (rand()*rand()) & mask;
410         } else {
411             value = rand() & mask;
412         }
413         is = intsetAdd(is,value,NULL);
414     }
415     return is;
416 }
417 
418 static void checkConsistency(intset *is) {
419     for (uint32_t i = 0; i < (intrev32ifbe(is->length)-1); i++) {
420         uint32_t encoding = intrev32ifbe(is->encoding);
421 
422         if (encoding == INTSET_ENC_INT16) {
423             int16_t *i16 = (int16_t*)is->contents;
424             assert(i16[i] < i16[i+1]);
425         } else if (encoding == INTSET_ENC_INT32) {
426             int32_t *i32 = (int32_t*)is->contents;
427             assert(i32[i] < i32[i+1]);
428         } else {
429             int64_t *i64 = (int64_t*)is->contents;
430             assert(i64[i] < i64[i+1]);
431         }
432     }
433 }
434 
435 #define UNUSED(x) (void)(x)
436 int intsetTest(int argc, char **argv) {
437     uint8_t success;
438     int i;
439     intset *is;
440     srand(time(NULL));
441 
442     UNUSED(argc);
443     UNUSED(argv);
444 
445     printf("Value encodings: "); {
446         assert(_intsetValueEncoding(-32768) == INTSET_ENC_INT16);
447         assert(_intsetValueEncoding(+32767) == INTSET_ENC_INT16);
448         assert(_intsetValueEncoding(-32769) == INTSET_ENC_INT32);
449         assert(_intsetValueEncoding(+32768) == INTSET_ENC_INT32);
450         assert(_intsetValueEncoding(-2147483648) == INTSET_ENC_INT32);
451         assert(_intsetValueEncoding(+2147483647) == INTSET_ENC_INT32);
452         assert(_intsetValueEncoding(-2147483649) == INTSET_ENC_INT64);
453         assert(_intsetValueEncoding(+2147483648) == INTSET_ENC_INT64);
454         assert(_intsetValueEncoding(-9223372036854775808ull) ==
455                     INTSET_ENC_INT64);
456         assert(_intsetValueEncoding(+9223372036854775807ull) ==
457                     INTSET_ENC_INT64);
458         ok();
459     }
460 
461     printf("Basic adding: "); {
462         is = intsetNew();
463         is = intsetAdd(is,5,&success); assert(success);
464         is = intsetAdd(is,6,&success); assert(success);
465         is = intsetAdd(is,4,&success); assert(success);
466         is = intsetAdd(is,4,&success); assert(!success);
467         ok();
468     }
469 
470     printf("Large number of random adds: "); {
471         uint32_t inserts = 0;
472         is = intsetNew();
473         for (i = 0; i < 1024; i++) {
474             is = intsetAdd(is,rand()%0x800,&success);
475             if (success) inserts++;
476         }
477         assert(intrev32ifbe(is->length) == inserts);
478         checkConsistency(is);
479         ok();
480     }
481 
482     printf("Upgrade from int16 to int32: "); {
483         is = intsetNew();
484         is = intsetAdd(is,32,NULL);
485         assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT16);
486         is = intsetAdd(is,65535,NULL);
487         assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT32);
488         assert(intsetFind(is,32));
489         assert(intsetFind(is,65535));
490         checkConsistency(is);
491 
492         is = intsetNew();
493         is = intsetAdd(is,32,NULL);
494         assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT16);
495         is = intsetAdd(is,-65535,NULL);
496         assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT32);
497         assert(intsetFind(is,32));
498         assert(intsetFind(is,-65535));
499         checkConsistency(is);
500         ok();
501     }
502 
503     printf("Upgrade from int16 to int64: "); {
504         is = intsetNew();
505         is = intsetAdd(is,32,NULL);
506         assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT16);
507         is = intsetAdd(is,4294967295,NULL);
508         assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT64);
509         assert(intsetFind(is,32));
510         assert(intsetFind(is,4294967295));
511         checkConsistency(is);
512 
513         is = intsetNew();
514         is = intsetAdd(is,32,NULL);
515         assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT16);
516         is = intsetAdd(is,-4294967295,NULL);
517         assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT64);
518         assert(intsetFind(is,32));
519         assert(intsetFind(is,-4294967295));
520         checkConsistency(is);
521         ok();
522     }
523 
524     printf("Upgrade from int32 to int64: "); {
525         is = intsetNew();
526         is = intsetAdd(is,65535,NULL);
527         assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT32);
528         is = intsetAdd(is,4294967295,NULL);
529         assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT64);
530         assert(intsetFind(is,65535));
531         assert(intsetFind(is,4294967295));
532         checkConsistency(is);
533 
534         is = intsetNew();
535         is = intsetAdd(is,65535,NULL);
536         assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT32);
537         is = intsetAdd(is,-4294967295,NULL);
538         assert(intrev32ifbe(is->encoding) == INTSET_ENC_INT64);
539         assert(intsetFind(is,65535));
540         assert(intsetFind(is,-4294967295));
541         checkConsistency(is);
542         ok();
543     }
544 
545     printf("Stress lookups: "); {
546         long num = 100000, size = 10000;
547         int i, bits = 20;
548         long long start;
549         is = createSet(bits,size);
550         checkConsistency(is);
551 
552         start = usec();
553         for (i = 0; i < num; i++) intsetSearch(is,rand() % ((1<<bits)-1),NULL);
554         printf("%ld lookups, %ld element set, %lldusec\n",
555                num,size,usec()-start);
556     }
557 
558     printf("Stress add+delete: "); {
559         int i, v1, v2;
560         is = intsetNew();
561         for (i = 0; i < 0xffff; i++) {
562             v1 = rand() % 0xfff;
563             is = intsetAdd(is,v1,NULL);
564             assert(intsetFind(is,v1));
565 
566             v2 = rand() % 0xfff;
567             is = intsetRemove(is,v2,NULL);
568             assert(!intsetFind(is,v2));
569         }
570         checkConsistency(is);
571         ok();
572     }
573 
574     return 0;
575 }
576 #endif
577