對給定的鍵的鍵值(字符串或整數)進行位操作:如SETBIT/ GETBIT:設置或 獲取鍵值指定位的值(0或1); BITOP :對給的多個定鍵值按位進行AND OR XOR 以及NOT運算 等操作。
在存儲數據時,對於那些只有兩個取值的數據(比如性別)按二進制位來存儲比存放對應的整數或者字符等能節約很多空間。
具體命令實現:
BITCOUNT:
計算長度爲 count 的二進制數組指針 s 被設置爲 1 的位的數量。
size_t redisPopcount(void *s, long count)
其中一種計算方法可見:http://blog.csdn.net/yuyixinye/article/details/40657773
SETBIT / GETBIT命令的基本思想:
***把偏移量bitoffset(給定鍵值的目標位)轉化爲第byte個字節的第bit個位 的組合,
***然後在字符串(爲整數編碼的先轉化爲字符串編碼)中取出(或設置)第bitoffset個字符的第bit位即可
***注意: 要取的位是在字符串中從左到右的順序計算的,而在取某個字節的bit位時是按右到左的順序計算的,因此 需要轉換
按位AND OR XOR 以及NOT 等命令:
優化處理措施:在鍵的數量比較少時,把鍵值字符串劃分爲整數個32位 + 最後的殘餘(小於32位)位數組成。對前面的整數倍的32位的,每次循環處理4個字節(32位),由於對每個鍵值字符串,這4個字節是連着存放的,因此可以一次載入到緩存中,然後按位進行處理; 而對於後面的小於32位的則每次循環只處理一個字節。
<span style="font-size:18px;">/* SETBIT key offset bitvalue */
//與GET命令實現思路一致: 找到要設置的字節的目標位,然後記錄下原來的該位的值,最後把該位設置爲目標值
void setbitCommand(redisClient *c) {
robj *o;
char *err = "bit is not an integer or out of range";
size_t bitoffset;
int byte, bit;
int byteval, bitval;
long on;
// 獲取 offset 參數
if (getBitOffsetFromArgument(c,c->argv[2],&bitoffset) != REDIS_OK)
return;
// 獲取 value 參數
if (getLongFromObjectOrReply(c,c->argv[3],&on,err) != REDIS_OK)
return;
/* Bits can only be set or cleared... */
// value 參數的值只能是 0 或者 1 ,否則返回錯誤
if (on & ~1) {//位運算的結果,按非1(即全零)即1(至少有一位爲1)處理
addReplyError(c,err);
return;
}
// 查找字符串對象
o = lookupKeyWrite(c->db,c->argv[1]);
if (o == NULL) {
// 對象不存在,創建一個空字符串對象
o = createObject(REDIS_STRING,sdsempty());
// 並添加到數據庫
dbAdd(c->db,c->argv[1],o);
} else {
// 對象存在,檢查類型是否字符串
if (checkType(c,o,REDIS_STRING)) return;
o = dbUnshareStringValue(c->db,c->argv[1],o);
}
/* Grow sds value to the right length if necessary */
// 計算容納 offset 參數所指定的偏移量所需的字節數
// 如果 o 對象的字節不夠長的話,就擴展它
// 長度的計算公式是 bitoffset >> 3 + 1
// 比如 30 >> 3 + 1 = 4 ,也即是爲了設置 offset 30 ,
// 我們需要創建一個 4 字節(32 位長的 SDS)
byte = bitoffset >> 3;
o->ptr = sdsgrowzero(o->ptr,byte+1);
/* Get current values */
// 將指針定位到要設置的位所在的字節上
byteval = ((uint8_t*)o->ptr)[byte];
// 定位到要設置的位上面
bit = 7 - (bitoffset & 0x7);
// 記錄位現在的值
bitval = byteval & (1 << bit);
/* Update byte with new bit value and return original value */
// 更新字節中的位,設置它的值爲 on 參數的值
byteval &= ~(1 << bit);//把要設置的位設爲0
byteval |= ((on & 0x1) << bit);//把要這是的位置爲設定值
((uint8_t*)o->ptr)[byte] = byteval;
// 發送數據庫修改通知
signalModifiedKey(c->db,c->argv[1]);
notifyKeyspaceEvent(REDIS_NOTIFY_STRING,"setbit",c->argv[1],c->db->id);
server.dirty++;
// 向客戶端返回位原來的值
addReply(c, bitval ? shared.cone : shared.czero);
}
/* GETBIT key offset */
//把偏移量bitoffset轉化爲第byte字節的第bit位 的組合,
//然後在字符串(爲整數編碼的先轉化爲字符串編碼)中取出的bitoffset個字符的第bit位即可
//注意: 要取的位是在字符串中從左到右的順序計算的,
//而在取某個字節的bit位時是按右到左的順序計算的,因此需要轉換
void getbitCommand(redisClient *c) {
robj *o;
char llbuf[32];
size_t bitoffset;
size_t byte, bit;
size_t bitval = 0;
// 讀取 offset 參數
if (getBitOffsetFromArgument(c,c->argv[2],&bitoffset) != REDIS_OK)
return;
// 查找對象,並進行類型檢查
if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
checkType(c,o,REDIS_STRING)) return;
// 計算出 offset 所指定的位所在的字節
byte = bitoffset >> 3;
// 計算出位所在的位置
bit = 7 - (bitoffset & 0x7);//注意: 要取的位是在字符串中從左到右的順序計算的,
//而在取某個字節的bit位時是按右到左的順序計算的,因此需要轉換
// 取出位
if (sdsEncodedObject(o)) {
// 字符串編碼,直接取值
if (byte < sdslen(o->ptr))
bitval = ((uint8_t*)o->ptr)[byte] & (1 << bit);
} else {
// 整數編碼,先轉換成字符串,再取值
if (byte < (size_t)ll2string(llbuf,sizeof(llbuf),(long)o->ptr))
bitval = llbuf[byte] & (1 << bit);
}
// 返回位
addReply(c, bitval ? shared.cone : shared.czero);
}
/* BITOP op_name target_key src_key1 src_key2 src_key3 ... src_keyN */
//把目標字符串進行給定的爲運算:
void bitopCommand(redisClient *c) {
char *opname = c->argv[1]->ptr;
robj *o, *targetkey = c->argv[2];
long op, j, numkeys;
robj **objects; /* Array of source objects. */
unsigned char **src; /* Array of source strings pointers. */
long *len, maxlen = 0; /* Array of length of src strings, and max len. */
long minlen = 0; /* Min len among the input keys. */
unsigned char *res = NULL; /* Resulting string. */
/* Parse the operation name. */
// 讀入 op 參數,確定要執行的操作
if ((opname[0] == 'a' || opname[0] == 'A') && !strcasecmp(opname,"and"))
op = BITOP_AND;
else if((opname[0] == 'o' || opname[0] == 'O') && !strcasecmp(opname,"or"))
op = BITOP_OR;
else if((opname[0] == 'x' || opname[0] == 'X') && !strcasecmp(opname,"xor"))
op = BITOP_XOR;
else if((opname[0] == 'n' || opname[0] == 'N') && !strcasecmp(opname,"not"))
op = BITOP_NOT;
else {
addReply(c,shared.syntaxerr);
return;
}
/* Sanity check: NOT accepts only a single key argument. */
// NOT 操作只能接受單個 key 輸入
if (op == BITOP_NOT && c->argc != 4) {
addReplyError(c,"BITOP NOT must be called with a single source key.");
return;
}
/* Lookup keys, and store pointers to the string objects into an array. */
// 查找輸入鍵,並將它們放入一個數組裏面
numkeys = c->argc - 3;
// 字符串數組,保存 sds 值
src = zmalloc(sizeof(unsigned char*) * numkeys);
// 長度數組,保存 sds 的長度
len = zmalloc(sizeof(long) * numkeys);
// 對象數組,保存字符串對象
objects = zmalloc(sizeof(robj*) * numkeys);
for (j = 0; j < numkeys; j++) {
// 查找對象
o = lookupKeyRead(c->db,c->argv[j+3]);
/* Handle non-existing keys as empty strings. */
// 不存在的鍵被視爲空字符串
if (o == NULL) {
objects[j] = NULL;
src[j] = NULL;
len[j] = 0;
minlen = 0;
continue;
}
/* Return an error if one of the keys is not a string. */
// 鍵不是字符串類型,返回錯誤,放棄執行操作
if (checkType(c,o,REDIS_STRING)) {
for (j = j-1; j >= 0; j--) {
if (objects[j])
decrRefCount(objects[j]);
}
zfree(src);
zfree(len);
zfree(objects);
return;
}
// 記錄對象
objects[j] = getDecodedObject(o);
// 記錄 sds
src[j] = objects[j]->ptr;
// 記錄 sds 長度
len[j] = sdslen(objects[j]->ptr);
// 記錄目前最長 sds 的長度
if (len[j] > maxlen) maxlen = len[j];
// 記錄目前最短 sds 的長度
if (j == 0 || len[j] < minlen) minlen = len[j];
}
/* Compute the bit operation, if at least one string is not empty. */
// 如果有至少一個非空字符串,那麼執行計算
if (maxlen) {
// 根據最大長度,創建一個 sds ,該 sds 的所有位都被設置爲 0
res = (unsigned char*) sdsnewlen(NULL,maxlen);
unsigned char output, byte;
long i;
/* Fast path: as far as we have data for all the input bitmaps we
* can take a fast path that performs much better than the
* vanilla algorithm. */
// 在鍵的數量比較少時,進行優化(每次處理4個字節,這4個字是連着存放的,個一次載入到緩存中): 處理前面的整數倍的32位的,後面的小於32位的正常處理
j = 0;
if (minlen && numkeys <= 16) {
unsigned long *lp[16];
unsigned long *lres = (unsigned long*) res;
/* Note: sds pointer is always aligned to 8 byte boundary. */
memcpy(lp,src,sizeof(unsigned long*)*numkeys);
memcpy(res,src[0],minlen);
/* Different branches per different operations for speed (sorry). */
// 當要處理的位大於等於 32 位時
// 每次載入 4*8 = 32 個位,然後對這些位進行計算,利用緩存,進行加速
if (op == BITOP_AND) {
while(minlen >= sizeof(unsigned long)*4) {
for (i = 1; i < numkeys; i++) {
lres[0] &= lp[i][0];
lres[1] &= lp[i][1];
lres[2] &= lp[i][2];
lres[3] &= lp[i][3];
lp[i]+=4;
}
lres+=4;
j += sizeof(unsigned long)*4;
minlen -= sizeof(unsigned long)*4;
}
} else if (op == BITOP_OR) {
while(minlen >= sizeof(unsigned long)*4) {
for (i = 1; i < numkeys; i++) {
lres[0] |= lp[i][0];
lres[1] |= lp[i][1];
lres[2] |= lp[i][2];
lres[3] |= lp[i][3];
lp[i]+=4;
}
lres+=4;
j += sizeof(unsigned long)*4;
minlen -= sizeof(unsigned long)*4;
}
} else if (op == BITOP_XOR) {
while(minlen >= sizeof(unsigned long)*4) {
for (i = 1; i < numkeys; i++) {
lres[0] ^= lp[i][0];
lres[1] ^= lp[i][1];
lres[2] ^= lp[i][2];
lres[3] ^= lp[i][3];
lp[i]+=4;
}
lres+=4;
j += sizeof(unsigned long)*4;
minlen -= sizeof(unsigned long)*4;
}
} else if (op == BITOP_NOT) {
while(minlen >= sizeof(unsigned long)*4) {
lres[0] = ~lres[0];
lres[1] = ~lres[1];
lres[2] = ~lres[2];
lres[3] = ~lres[3];
lres+=4;
j += sizeof(unsigned long)*4;
minlen -= sizeof(unsigned long)*4;
}
}
}
/* j is set to the next byte to process by the previous loop. */
// 以正常方式執行位運算(每次處理一個字節)
for (; j < maxlen; j++) {
output = (len[0] <= j) ? 0 : src[0][j];
if (op == BITOP_NOT) output = ~output;
// 遍歷所有輸入鍵,對所有輸入的 scr[i][j] 字節進行運算
for (i = 1; i < numkeys; i++) {
// 如果數組的長度不足,那麼相應的字節被假設爲 0
byte = (len[i] <= j) ? 0 : src[i][j];
switch(op) {
case BITOP_AND: output &= byte; break;
case BITOP_OR: output |= byte; break;
case BITOP_XOR: output ^= byte; break;
}
}
// 保存輸出
res[j] = output;
}
}
// 釋放資源
for (j = 0; j < numkeys; j++) {
if (objects[j])
decrRefCount(objects[j]);
}
zfree(src);
zfree(len);
zfree(objects);
/* Store the computed value into the target key */
if (maxlen) {
// 保存結果到指定鍵
o = createObject(REDIS_STRING,res);
setKey(c->db,targetkey,o);
notifyKeyspaceEvent(REDIS_NOTIFY_STRING,"set",targetkey,c->db->id);
decrRefCount(o);
} else if (dbDelete(c->db,targetkey)) {
// 輸入爲空,沒有產生結果,僅僅刪除指定鍵
signalModifiedKey(c->db,targetkey);
notifyKeyspaceEvent(REDIS_NOTIFY_GENERIC,"del",targetkey,c->db->id);
}
server.dirty++;
addReplyLongLong(c,maxlen); /* Return the output string length in bytes. */
}
</span>