English | 中文版
[TOC]
| Function | Purpose | Time Complexity |
|---|---|---|
| intsetNew | Create a new integer set | |
| intsetAdd | Add the given element into the set | |
| intsetRemove | Remove the given element from the set | |
| intsetFind | Check whether a value exists in the set | Because the underlying array is ordered, binary search is used, so |
| intsetRandom | Return a random element from the set | |
| intsetGet | Get the element at a given index | |
| intsetLen | Return number of elements in the set | |
| intsetBlobLen | Return memory bytes used by the set |
// integer set
typedef struct intset {
uint32_t encoding; // encoding: INTSET_ENC_INT16, INTSET_ENC_INT32, INTSET_ENC_INT64
uint32_t length; // number of elements in the set, length of contents
int8_t contents[]; // array storing elements in ascending order without duplicates (actual item size depends on encoding)
} intset;#define INTSET_ENC_INT16 (sizeof(int16_t)) // int16_t encoding, [-32768, 32767]
#define INTSET_ENC_INT32 (sizeof(int32_t)) // int32_t encoding, [-2147483648, 2147483647]
#define INTSET_ENC_INT64 (sizeof(int64_t)) // int64_t encoding, [-9223372036854775808, 9223372036854775807]When adding an element that exceeds the current encoding range, the integer set must be upgraded before inserting the new element.
The upgrade-and-insert process consists of the following steps:
- Resize the underlying array to fit the new element type and allocate space for the new element.
- Convert all existing elements in the array to the new element type and place them in the correct positions, maintaining the array's sorted order during placement.
- Insert the new element into the underlying array.
Example: inserting the int32 value 65535 into an INTSET_ENC_INT16 set.
Placement rules after upgrade:
- If the new element is smaller than all existing elements, it is placed at the beginning.
- If the new element is larger than all existing elements, it is placed at the end.
Set before insertion:
| intset | encoding | length | contents |
|---|---|---|---|
| INTSET_ENC_INT16 | 3 | ` |
Set after insertion:
| intset | encoding | length | contents |
|---|---|---|---|
| INTSET_ENC_INT32 | 4 | ` |
-
Improved flexibility
The integer set can automatically upgrade the underlying array to accommodate new elements, so you can insert int16_t, int32_t or int64_t values without type errors.
-
Memory savings
[1] Huang Jianhong. Redis Design and Implementation







