]> git.saurik.com Git - redis.git/blob - src/bitop.c
2b26265d7be4860a7b5b2b776571fb1c4b54947e
[redis.git] / src / bitop.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 = s;
34 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};
35
36 /* We can finally count bits. */
37 while(count--) bits += bitsinbyte[*p++];
38 return bits;
39 }
40
41 /* -----------------------------------------------------------------------------
42 * Bits related string commands: GETBIT, SETBIT, BITCOUNT, BITOP.
43 * -------------------------------------------------------------------------- */
44
45 #define BITOP_AND 0
46 #define BITOP_OR 1
47 #define BITOP_XOR 2
48 #define BITOP_NOT 3
49
50 /* SETBIT key offset bitvalue */
51 void setbitCommand(redisClient *c) {
52 robj *o;
53 char *err = "bit is not an integer or out of range";
54 size_t bitoffset;
55 int byte, bit;
56 int byteval, bitval;
57 long on;
58
59 if (getBitOffsetFromArgument(c,c->argv[2],&bitoffset) != REDIS_OK)
60 return;
61
62 if (getLongFromObjectOrReply(c,c->argv[3],&on,err) != REDIS_OK)
63 return;
64
65 /* Bits can only be set or cleared... */
66 if (on & ~1) {
67 addReplyError(c,err);
68 return;
69 }
70
71 o = lookupKeyWrite(c->db,c->argv[1]);
72 if (o == NULL) {
73 o = createObject(REDIS_STRING,sdsempty());
74 dbAdd(c->db,c->argv[1],o);
75 } else {
76 if (checkType(c,o,REDIS_STRING)) return;
77
78 /* Create a copy when the object is shared or encoded. */
79 if (o->refcount != 1 || o->encoding != REDIS_ENCODING_RAW) {
80 robj *decoded = getDecodedObject(o);
81 o = createStringObject(decoded->ptr, sdslen(decoded->ptr));
82 decrRefCount(decoded);
83 dbOverwrite(c->db,c->argv[1],o);
84 }
85 }
86
87 /* Grow sds value to the right length if necessary */
88 byte = bitoffset >> 3;
89 o->ptr = sdsgrowzero(o->ptr,byte+1);
90
91 /* Get current values */
92 byteval = ((char*)o->ptr)[byte];
93 bit = 7 - (bitoffset & 0x7);
94 bitval = byteval & (1 << bit);
95
96 /* Update byte with new bit value and return original value */
97 byteval &= ~(1 << bit);
98 byteval |= ((on & 0x1) << bit);
99 ((char*)o->ptr)[byte] = byteval;
100 signalModifiedKey(c->db,c->argv[1]);
101 server.dirty++;
102 addReply(c, bitval ? shared.cone : shared.czero);
103 }
104
105 /* GETBIT key offset */
106 void getbitCommand(redisClient *c) {
107 robj *o;
108 char llbuf[32];
109 size_t bitoffset;
110 size_t byte, bit;
111 size_t bitval = 0;
112
113 if (getBitOffsetFromArgument(c,c->argv[2],&bitoffset) != REDIS_OK)
114 return;
115
116 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
117 checkType(c,o,REDIS_STRING)) return;
118
119 byte = bitoffset >> 3;
120 bit = 7 - (bitoffset & 0x7);
121 if (o->encoding != REDIS_ENCODING_RAW) {
122 if (byte < (size_t)ll2string(llbuf,sizeof(llbuf),(long)o->ptr))
123 bitval = llbuf[byte] & (1 << bit);
124 } else {
125 if (byte < sdslen(o->ptr))
126 bitval = ((char*)o->ptr)[byte] & (1 << bit);
127 }
128
129 addReply(c, bitval ? shared.cone : shared.czero);
130 }
131
132 /* BITOP op_name target_key src_key1 src_key2 src_key3 ... src_keyN */
133 void bitopCommand(redisClient *c) {
134 char *opname = c->argv[1]->ptr;
135 robj *o, *targetkey = c->argv[2];
136 long op, j, numkeys;
137 unsigned char **src; /* Array of source strings pointers. */
138 long *len, maxlen = 0; /* Array of length of src strings, and max len. */
139 unsigned char *res = NULL; /* Resulting string. */
140
141 /* Parse the operation name. */
142 if ((opname[0] == 'a' || opname[0] == 'A') && !strcasecmp(opname,"and"))
143 op = BITOP_AND;
144 else if((opname[0] == 'o' || opname[0] == 'O') && !strcasecmp(opname,"or"))
145 op = BITOP_OR;
146 else if((opname[0] == 'x' || opname[0] == 'X') && !strcasecmp(opname,"xor"))
147 op = BITOP_XOR;
148 else if((opname[0] == 'n' || opname[0] == 'N') && !strcasecmp(opname,"not"))
149 op = BITOP_NOT;
150 else {
151 addReply(c,shared.syntaxerr);
152 return;
153 }
154
155 /* Sanity check: NOT accepts only a single key argument. */
156 if (op == BITOP_NOT && c->argc != 4) {
157 addReplyError(c,"BITOP NOT must be called with a single source key.");
158 return;
159 }
160
161 /* Lookup keys, and store pointers to the string objects into an array. */
162 numkeys = c->argc - 3;
163 src = zmalloc(sizeof(unsigned char*) * numkeys);
164 len = zmalloc(sizeof(long) * numkeys);
165 for (j = 0; j < numkeys; j++) {
166 o = lookupKeyRead(c->db,c->argv[j+3]);
167 /* Handle non-existing keys as empty strings. */
168 if (o == NULL) {
169 src[j] = NULL;
170 len[j] = 0;
171 continue;
172 }
173 /* Return an error if one of the keys is not a string. */
174 if (checkType(c,o,REDIS_STRING)) {
175 zfree(src);
176 zfree(len);
177 return;
178 }
179 src[j] = o->ptr;
180 len[j] = sdslen(o->ptr);
181 if (len[j] > maxlen) maxlen = len[j];
182 }
183
184 /* Compute the bit operation, if at least one string is not empty. */
185 if (maxlen) {
186 res = (unsigned char*) sdsnewlen(NULL,maxlen);
187 unsigned char output, byte;
188 long i;
189
190 for (j = 0; j < maxlen; j++) {
191 output = (len[0] <= j) ? 0 : src[0][j];
192 if (op == BITOP_NOT) output = ~output;
193 for (i = 1; i < numkeys; i++) {
194 byte = (len[i] <= j) ? 0 : src[i][j];
195 switch(op) {
196 case BITOP_AND: output &= byte; break;
197 case BITOP_OR: output |= byte; break;
198 case BITOP_XOR: output ^= byte; break;
199 }
200 }
201 res[j] = output;
202 }
203 }
204 zfree(src);
205 zfree(len);
206
207 /* Store the computed value into the target key */
208 if (maxlen) {
209 o = createObject(REDIS_STRING,res);
210 setKey(c->db,targetkey,o);
211 decrRefCount(o);
212 } else if (dbDelete(c->db,targetkey)) {
213 signalModifiedKey(c->db,targetkey);
214 }
215 server.dirty++;
216 addReplyLongLong(c,maxlen); /* Return the output string length in bytes. */
217 }
218
219 /* BITCOUNT key [start end] */
220 void bitcountCommand(redisClient *c) {
221 robj *o;
222 long start, end;
223 unsigned char *p;
224 char llbuf[32];
225 size_t strlen;
226
227 /* Lookup, check for type, and return 0 for non existing keys. */
228 if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
229 checkType(c,o,REDIS_STRING)) return;
230
231 /* Set the 'p' pointer to the string, that can be just a stack allocated
232 * array if our string was integer encoded. */
233 if (o->encoding == REDIS_ENCODING_INT) {
234 p = (unsigned char*) llbuf;
235 strlen = ll2string(llbuf,sizeof(llbuf),(long)o->ptr);
236 } else {
237 p = (unsigned char*) o->ptr;
238 strlen = sdslen(o->ptr);
239 }
240
241 /* Parse start/end range if any. */
242 if (c->argc == 4) {
243 if (getLongFromObjectOrReply(c,c->argv[2],&start,NULL) != REDIS_OK)
244 return;
245 if (getLongFromObjectOrReply(c,c->argv[3],&end,NULL) != REDIS_OK)
246 return;
247 /* Convert negative indexes */
248 if (start < 0) start = strlen+start;
249 if (end < 0) end = strlen+end;
250 if (start < 0) start = 0;
251 if (end < 0) end = 0;
252 if ((unsigned)end >= strlen) end = strlen-1;
253 } else if (c->argc == 2) {
254 /* The whole string. */
255 start = 0;
256 end = strlen-1;
257 } else {
258 /* Syntax error. */
259 addReply(c,shared.syntaxerr);
260 return;
261 }
262
263 /* Precondition: end >= 0 && end < strlen, so the only condition where
264 * zero can be returned is: start > end. */
265 if (start > end) {
266 addReply(c,shared.czero);
267 } else {
268 long bytes = end-start+1;
269
270 addReplyLongLong(c,popcount(p+start,bytes));
271 }
272 }