]> git.saurik.com Git - redis.git/blob - src/bitops.c
2f62ccc460494bd0f12b6482cc3fceea545f950c
[redis.git] / src / bitops.c
1 #include "redis.h"
2
3 /* -----------------------------------------------------------------------------
4 * Helpers and low level bit functions.
5 * -------------------------------------------------------------------------- */
6
7 /* This helper function used by GETBIT / SETBIT parses the bit offset arguemnt
8 * making sure an error is returned if it is negative or if it overflows
9 * Redis 512 MB limit for the string value. */
10 static int getBitOffsetFromArgument(redisClient *c, robj *o, size_t *offset) {
11 long long loffset;
12 char *err = "bit offset is not an integer or out of range";
13
14 if (getLongLongFromObjectOrReply(c,o,&loffset,err) != REDIS_OK)
15 return REDIS_ERR;
16
17 /* Limit offset to 512MB in bytes */
18 if ((loffset < 0) || ((unsigned long long)loffset >> 3) >= (512*1024*1024))
19 {
20 addReplyError(c,err);
21 return REDIS_ERR;
22 }
23
24 *offset = (size_t)loffset;
25 return REDIS_OK;
26 }
27
28 /* Count number of bits set in the binary array pointed by 's' and long
29 * 'count' bytes. The implementation of this function is required to
30 * work with a input string length up to 512 MB. */
31 long popcount(void *s, long count) {
32 long bits = 0;
33 unsigned char *p;
34 uint32_t *p4 = s;
35 static const unsigned char bitsinbyte[256] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8};
36
37 /* Count bits 16 bytes at a time */
38 while(count>=16) {
39 uint32_t aux1, aux2, aux3, aux4;
40
41 aux1 = *p4++;
42 aux2 = *p4++;
43 aux3 = *p4++;
44 aux4 = *p4++;
45 count -= 16;
46
47 aux1 = aux1 - ((aux1 >> 1) & 0x55555555);
48 aux1 = (aux1 & 0x33333333) + ((aux1 >> 2) & 0x33333333);
49 aux2 = aux2 - ((aux2 >> 1) & 0x55555555);
50 aux2 = (aux2 & 0x33333333) + ((aux2 >> 2) & 0x33333333);
51 aux3 = aux3 - ((aux3 >> 1) & 0x55555555);
52 aux3 = (aux3 & 0x33333333) + ((aux3 >> 2) & 0x33333333);
53 aux4 = aux4 - ((aux4 >> 1) & 0x55555555);
54 aux4 = (aux4 & 0x33333333) + ((aux4 >> 2) & 0x33333333);
55 bits += ((((aux1 + (aux1 >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24) +
56 ((((aux2 + (aux2 >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24) +
57 ((((aux3 + (aux3 >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24) +
58 ((((aux4 + (aux4 >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24);
59 }
60 /* Count the remaining bytes */
61 p = (unsigned char*)p4;
62 while(count--) bits += bitsinbyte[*p++];
63 return bits;
64 }
65
66 /* -----------------------------------------------------------------------------
67 * Bits related string commands: GETBIT, SETBIT, BITCOUNT, BITOP.
68 * -------------------------------------------------------------------------- */
69
70 #define BITOP_AND 0
71 #define BITOP_OR 1
72 #define BITOP_XOR 2
73 #define BITOP_NOT 3
74
75 /* SETBIT key offset bitvalue */
76 void setbitCommand(redisClient *c) {
77 robj *o;
78 char *err = "bit is not an integer or out of range";
79 size_t bitoffset;
80 int byte, bit;
81 int byteval, bitval;
82 long on;
83
84 if (getBitOffsetFromArgument(c,c->argv[2],&bitoffset) != REDIS_OK)
85 return;
86
87 if (getLongFromObjectOrReply(c,c->argv[3],&on,err) != REDIS_OK)
88 return;
89
90 /* Bits can only be set or cleared... */
91 if (on & ~1) {
92 addReplyError(c,err);
93 return;
94 }
95
96 o = lookupKeyWrite(c->db,c->argv[1]);
97 if (o == NULL) {
98 o = createObject(REDIS_STRING,sdsempty());
99 dbAdd(c->db,c->argv[1],o);
100 } else {
101 if (checkType(c,o,REDIS_STRING)) return;
102
103 /* Create a copy when the object is shared or encoded. */
104 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
105 robj *decoded = getDecodedObject(o);
106 o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
107 decrRefCount(decoded);
108 dbOverwrite(c->db,c->argv[1],o);
109 }
110 }
111
112 /* Grow sds value to the right length if necessary */
113 byte = bitoffset >> 3;
114 o->ptr = sdsgrowzero(o->ptr,byte+1);
115
116 /* Get current values */
117 byteval = ((char*)o->ptr)[byte];
118 bit = 7 - (bitoffset & 0x7);
119 bitval = byteval & (1 << bit);
120
121 /* Update byte with new bit value and return original value */
122 byteval &= ~(1 << bit);
123 byteval |= ((on & 0x1) << bit);
124 ((char*)o->ptr)[byte] = byteval;
125 signalModifiedKey(c->db,c->argv[1]);
126 server.dirty++;
127 addReply(c, bitval ? shared.cone : shared.czero);
128 }
129
130 /* GETBIT key offset */
131 void getbitCommand(redisClient *c) {
132 robj *o;
133 char llbuf[32];
134 size_t bitoffset;
135 size_t byte, bit;
136 size_t bitval = 0;
137
138 if (getBitOffsetFromArgument(c,c->argv[2],&bitoffset) != REDIS_OK)
139 return;
140
141 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
142 checkType(c,o,REDIS_STRING)) return;
143
144 byte = bitoffset >> 3;
145 bit = 7 - (bitoffset & 0x7);
146 if (o->encoding != REDIS_ENCODING_RAW) {
147 if (byte < (size_t)ll2string(llbuf,sizeof(llbuf),(long)o->ptr))
148 bitval = llbuf[byte] & (1 << bit);
149 } else {
150 if (byte < sdslen(o->ptr))
151 bitval = ((char*)o->ptr)[byte] & (1 << bit);
152 }
153
154 addReply(c, bitval ? shared.cone : shared.czero);
155 }
156
157 /* BITOP op_name target_key src_key1 src_key2 src_key3 ... src_keyN */
158 void bitopCommand(redisClient *c) {
159 char *opname = c->argv[1]->ptr;
160 robj *o, *targetkey = c->argv[2];
161 long op, j, numkeys;
162 robj **objects; /* Array of soruce objects. */
163 unsigned char **src; /* Array of source strings pointers. */
164 long *len, maxlen = 0; /* Array of length of src strings, and max len. */
165 unsigned char *res = NULL; /* Resulting string. */
166
167 /* Parse the operation name. */
168 if ((opname[0] == 'a' || opname[0] == 'A') && !strcasecmp(opname,"and"))
169 op = BITOP_AND;
170 else if((opname[0] == 'o' || opname[0] == 'O') && !strcasecmp(opname,"or"))
171 op = BITOP_OR;
172 else if((opname[0] == 'x' || opname[0] == 'X') && !strcasecmp(opname,"xor"))
173 op = BITOP_XOR;
174 else if((opname[0] == 'n' || opname[0] == 'N') && !strcasecmp(opname,"not"))
175 op = BITOP_NOT;
176 else {
177 addReply(c,shared.syntaxerr);
178 return;
179 }
180
181 /* Sanity check: NOT accepts only a single key argument. */
182 if (op == BITOP_NOT && c->argc != 4) {
183 addReplyError(c,"BITOP NOT must be called with a single source key.");
184 return;
185 }
186
187 /* Lookup keys, and store pointers to the string objects into an array. */
188 numkeys = c->argc - 3;
189 src = zmalloc(sizeof(unsigned char*) * numkeys);
190 len = zmalloc(sizeof(long) * numkeys);
191 objects = zmalloc(sizeof(robj*) * numkeys);
192 for (j = 0; j < numkeys; j++) {
193 o = lookupKeyRead(c->db,c->argv[j+3]);
194 /* Handle non-existing keys as empty strings. */
195 if (o == NULL) {
196 objects[j] = NULL;
197 src[j] = NULL;
198 len[j] = 0;
199 continue;
200 }
201 /* Return an error if one of the keys is not a string. */
202 if (checkType(c,o,REDIS_STRING)) {
203 for (j = j-1; j >= 0; j--) {
204 if (objects[j])
205 decrRefCount(objects[j]);
206 }
207 zfree(src);
208 zfree(len);
209 zfree(objects);
210 return;
211 }
212 objects[j] = getDecodedObject(o);
213 src[j] = objects[j]->ptr;
214 len[j] = sdslen(objects[j]->ptr);
215 if (len[j] > maxlen) maxlen = len[j];
216 }
217
218 /* Compute the bit operation, if at least one string is not empty. */
219 if (maxlen) {
220 res = (unsigned char*) sdsnewlen(NULL,maxlen);
221 unsigned char output, byte;
222 long i;
223
224 for (j = 0; j < maxlen; j++) {
225 output = (len[0] <= j) ? 0 : src[0][j];
226 if (op == BITOP_NOT) output = ~output;
227 for (i = 1; i < numkeys; i++) {
228 byte = (len[i] <= j) ? 0 : src[i][j];
229 switch(op) {
230 case BITOP_AND: output &= byte; break;
231 case BITOP_OR: output |= byte; break;
232 case BITOP_XOR: output ^= byte; break;
233 }
234 }
235 res[j] = output;
236 }
237 }
238 for (j = 0; j < numkeys; j++) {
239 if (objects[j])
240 decrRefCount(objects[j]);
241 }
242 zfree(src);
243 zfree(len);
244 zfree(objects);
245
246 /* Store the computed value into the target key */
247 if (maxlen) {
248 o = createObject(REDIS_STRING,res);
249 setKey(c->db,targetkey,o);
250 decrRefCount(o);
251 } else if (dbDelete(c->db,targetkey)) {
252 signalModifiedKey(c->db,targetkey);
253 }
254 server.dirty++;
255 addReplyLongLong(c,maxlen); /* Return the output string length in bytes. */
256 }
257
258 /* BITCOUNT key [start end] */
259 void bitcountCommand(redisClient *c) {
260 robj *o;
261 long start, end;
262 unsigned char *p;
263 char llbuf[32];
264 size_t strlen;
265
266 /* Lookup, check for type, and return 0 for non existing keys. */
267 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
268 checkType(c,o,REDIS_STRING)) return;
269
270 /* Set the 'p' pointer to the string, that can be just a stack allocated
271 * array if our string was integer encoded. */
272 if (o->encoding == REDIS_ENCODING_INT) {
273 p = (unsigned char*) llbuf;
274 strlen = ll2string(llbuf,sizeof(llbuf),(long)o->ptr);
275 } else {
276 p = (unsigned char*) o->ptr;
277 strlen = sdslen(o->ptr);
278 }
279
280 /* Parse start/end range if any. */
281 if (c->argc == 4) {
282 if (getLongFromObjectOrReply(c,c->argv[2],&start,NULL) != REDIS_OK)
283 return;
284 if (getLongFromObjectOrReply(c,c->argv[3],&end,NULL) != REDIS_OK)
285 return;
286 /* Convert negative indexes */
287 if (start < 0) start = strlen+start;
288 if (end < 0) end = strlen+end;
289 if (start < 0) start = 0;
290 if (end < 0) end = 0;
291 if ((unsigned)end >= strlen) end = strlen-1;
292 } else if (c->argc == 2) {
293 /* The whole string. */
294 start = 0;
295 end = strlen-1;
296 } else {
297 /* Syntax error. */
298 addReply(c,shared.syntaxerr);
299 return;
300 }
301
302 /* Precondition: end >= 0 && end < strlen, so the only condition where
303 * zero can be returned is: start > end. */
304 if (start > end) {
305 addReply(c,shared.czero);
306 } else {
307 long bytes = end-start+1;
308
309 addReplyLongLong(c,popcount(p+start,bytes));
310 }
311 }