]> git.saurik.com Git - redis.git/blob - zipmap.c
8c7a79a8dd0a4a73c9b0521f626821cdb3bbf8cb
[redis.git] / zipmap.c
1 /* String -> String Map data structure optimized for size.
2 * This file implements a data structure mapping strings to other strings
3 * implementing an O(n) lookup data structure designed to be very memory
4 * efficient.
5 *
6 * The Redis Hash type uses this data structure for hashes composed of a small
7 * number of elements, to switch to an hash table once a given number of
8 * elements is reached.
9 *
10 * Given that many times Redis Hashes are used to represent objects composed
11 * of few fields, this is a very big win in terms of used memory.
12 *
13 * --------------------------------------------------------------------------
14 *
15 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are met:
20 *
21 * * Redistributions of source code must retain the above copyright notice,
22 * this list of conditions and the following disclaimer.
23 * * Redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution.
26 * * Neither the name of Redis nor the names of its contributors may be used
27 * to endorse or promote products derived from this software without
28 * specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
31 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
34 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
35 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
36 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
40 * POSSIBILITY OF SUCH DAMAGE.
41 */
42
43 /* Memory layout of a zipmap, for the map "foo" => "bar", "hello" => "world":
44 *
45 * <status><len>"foo"<len><free>"bar"<len>"hello"<len><free>"world"
46 *
47 * <status> is 1 byte status. Currently only 1 bit is used: if the least
48 * significant bit is set, it means the zipmap needs to be defragmented.
49 *
50 * <len> is the length of the following string (key or value).
51 * <len> lengths are encoded in a single value or in a 5 bytes value.
52 * If the first byte value (as an unsigned 8 bit value) is between 0 and
53 * 252, it's a single-byte length. If it is 253 then a four bytes unsigned
54 * integer follows (in the host byte ordering). A value fo 255 is used to
55 * signal the end of the hash. The special value 254 is used to mark
56 * empty space that can be used to add new key/value pairs.
57 *
58 * <free> is the number of free unused bytes
59 * after the string, resulting from modification of values associated to a
60 * key (for instance if "foo" is set to "bar', and later "foo" will be se to
61 * "hi", I'll have a free byte to use if the value will enlarge again later,
62 * or even in order to add a key/value pair if it fits.
63 *
64 * <free> is always an unsigned 8 bit number, because if after an
65 * update operation there are more than a few free bytes, they'll be converted
66 * into empty space prefixed by the special value 254.
67 *
68 * The most compact representation of the above two elements hash is actually:
69 *
70 * "\x00\x03foo\x03\x00bar\x05hello\x05\x00world\xff"
71 *
72 * Empty space is marked using a 254 bytes + a <len> (coded as already
73 * specified). The length includes the 254 bytes in the count and the
74 * space taken by the <len> field. So for instance removing the "foo" key
75 * from the zipmap above will lead to the following representation:
76 *
77 * "\x00\xfd\x10........\x05hello\x05\x00world\xff"
78 *
79 * Note that because empty space, keys, values, are all prefixed length
80 * "objects", the lookup will take O(N) where N is the numeber of elements
81 * in the zipmap and *not* the number of bytes needed to represent the zipmap.
82 * This lowers the constant times considerably.
83 */
84
85 #include <stdio.h>
86 #include <string.h>
87 #include <assert.h>
88 #include "zmalloc.h"
89
90 #define ZIPMAP_BIGLEN 253
91 #define ZIPMAP_EMPTY 254
92 #define ZIPMAP_END 255
93
94 #define ZIPMAP_STATUS_FRAGMENTED 1
95
96 /* The following defines the max value for the <free> field described in the
97 * comments above, that is, the max number of trailing bytes in a value. */
98 #define ZIPMAP_VALUE_MAX_FREE 5
99
100 /* The following macro returns the number of bytes needed to encode the length
101 * for the integer value _l, that is, 1 byte for lengths < ZIPMAP_BIGLEN and
102 * 5 bytes for all the other lengths. */
103 #define ZIPMAP_LEN_BYTES(_l) (((_l) < ZIPMAP_BIGLEN) ? 1 : sizeof(unsigned int)+1)
104
105 /* Create a new empty zipmap. */
106 unsigned char *zipmapNew(void) {
107 unsigned char *zm = zmalloc(2);
108
109 zm[0] = 0; /* Length */
110 zm[1] = ZIPMAP_END;
111 return zm;
112 }
113
114 /* Decode the encoded length pointed by 'p' */
115 static unsigned int zipmapDecodeLength(unsigned char *p) {
116 unsigned int len = *p;
117
118 if (len < ZIPMAP_BIGLEN) return len;
119 memcpy(&len,p+1,sizeof(unsigned int));
120 return len;
121 }
122
123 /* Encode the length 'l' writing it in 'p'. If p is NULL it just returns
124 * the amount of bytes required to encode such a length. */
125 static unsigned int zipmapEncodeLength(unsigned char *p, unsigned int len) {
126 if (p == NULL) {
127 return ZIPMAP_LEN_BYTES(len);
128 } else {
129 if (len < ZIPMAP_BIGLEN) {
130 p[0] = len;
131 return 1;
132 } else {
133 p[0] = ZIPMAP_BIGLEN;
134 memcpy(p+1,&len,sizeof(len));
135 return 1+sizeof(len);
136 }
137 }
138 }
139
140 /* Search for a matching key, returning a pointer to the entry inside the
141 * zipmap. Returns NULL if the key is not found.
142 *
143 * If NULL is returned, and totlen is not NULL, it is set to the entire
144 * size of the zimap, so that the calling function will be able to
145 * reallocate the original zipmap to make room for more entries.
146 *
147 * If NULL is returned, and freeoff and freelen are not NULL, they are set
148 * to the offset of the first empty space that can hold '*freelen' bytes
149 * (freelen is an integer pointer used both to signal the required length
150 * and to get the reply from the function). If there is not a suitable
151 * free space block to hold the requested bytes, *freelen is set to 0. */
152 static unsigned char *zipmapLookupRaw(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned int *totlen) {
153 unsigned char *p = zm+1, *k = NULL;
154 unsigned int l;
155
156 while(*p != ZIPMAP_END) {
157 unsigned char free;
158
159 /* Match or skip the key */
160 l = zipmapDecodeLength(p);
161 if (k == NULL && l == klen && !memcmp(p+1,key,l)) {
162 /* Only return when the user doesn't care
163 * for the total length of the zipmap. */
164 if (totlen != NULL) {
165 k = p;
166 } else {
167 return p;
168 }
169 }
170 p += zipmapEncodeLength(NULL,l) + l;
171 /* Skip the value as well */
172 l = zipmapDecodeLength(p);
173 p += zipmapEncodeLength(NULL,l);
174 free = p[0];
175 p += l+1+free; /* +1 to skip the free byte */
176 }
177 if (totlen != NULL) *totlen = (unsigned int)(p-zm)+1;
178 return k;
179 }
180
181 static unsigned long zipmapRequiredLength(unsigned int klen, unsigned int vlen) {
182 unsigned int l;
183
184 l = klen+vlen+3;
185 if (klen >= ZIPMAP_BIGLEN) l += 4;
186 if (vlen >= ZIPMAP_BIGLEN) l += 4;
187 return l;
188 }
189
190 /* Return the total amount used by a key (encoded length + payload) */
191 static unsigned int zipmapRawKeyLength(unsigned char *p) {
192 unsigned int l = zipmapDecodeLength(p);
193
194 return zipmapEncodeLength(NULL,l) + l;
195 }
196
197 /* Return the total amount used by a value
198 * (encoded length + single byte free count + payload) */
199 static unsigned int zipmapRawValueLength(unsigned char *p) {
200 unsigned int l = zipmapDecodeLength(p);
201 unsigned int used;
202
203 used = zipmapEncodeLength(NULL,l);
204 used += p[used] + 1 + l;
205 return used;
206 }
207
208 /* If 'p' points to a key, this function returns the total amount of
209 * bytes used to store this entry (entry = key + associated value + trailing
210 * free space if any). */
211 static unsigned int zipmapRawEntryLength(unsigned char *p) {
212 unsigned int l = zipmapRawKeyLength(p);
213
214 return l + zipmapRawValueLength(p+l);
215 }
216
217 static inline unsigned char *zipmapResize(unsigned char *zm, unsigned int len) {
218 zm = zrealloc(zm, len);
219 zm[len-1] = ZIPMAP_END;
220 return zm;
221 }
222
223 /* Set key to value, creating the key if it does not already exist.
224 * If 'update' is not NULL, *update is set to 1 if the key was
225 * already preset, otherwise to 0. */
226 unsigned char *zipmapSet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char *val, unsigned int vlen, int *update) {
227 unsigned int zmlen;
228 unsigned int freelen, reqlen = zipmapRequiredLength(klen,vlen);
229 unsigned int empty, vempty;
230 unsigned char *p;
231
232 freelen = reqlen;
233 if (update) *update = 0;
234 p = zipmapLookupRaw(zm,key,klen,&zmlen);
235 if (p == NULL) {
236 /* Key not found: enlarge */
237 zm = zipmapResize(zm, zmlen+reqlen);
238 p = zm+zmlen-1;
239 zmlen = zmlen+reqlen;
240
241 /* Increase zipmap length (this is an insert) */
242 if (zm[0] < ZIPMAP_BIGLEN) zm[0]++;
243 } else {
244 unsigned char *b = p;
245
246 /* Key found. Is there enough space for the new value? */
247 /* Compute the total length: */
248 if (update) *update = 1;
249 freelen = zipmapRawKeyLength(b);
250 b += freelen;
251 freelen += zipmapRawValueLength(b);
252 if (freelen < reqlen) {
253 /* Move remaining entries to the current position, so this
254 * pair can be appended. Note: the +1 in memmove is caused
255 * by the end-of-zipmap byte. */
256 memmove(p, p+freelen, zmlen-((p-zm)+freelen+1));
257 zm = zipmapResize(zm, zmlen-freelen+reqlen);
258 p = zm+zmlen-1-freelen;
259 zmlen = zmlen-1-freelen+reqlen;
260 freelen = reqlen;
261 }
262 }
263
264 /* Ok we have a suitable block where to write the new key/value
265 * entry. */
266 empty = freelen-reqlen;
267 /* If there is too much free space mark it as a free block instead
268 * of adding it as trailing empty space for the value, as we want
269 * zipmaps to be very space efficient. */
270 if (empty >= ZIPMAP_VALUE_MAX_FREE) {
271 memmove(p+reqlen, p+freelen, zmlen-((p-zm)+freelen+1));
272 zmlen -= empty;
273 zm = zipmapResize(zm, zmlen);
274 vempty = 0;
275 } else {
276 vempty = empty;
277 }
278
279 /* Just write the key + value and we are done. */
280 /* Key: */
281 p += zipmapEncodeLength(p,klen);
282 memcpy(p,key,klen);
283 p += klen;
284 /* Value: */
285 p += zipmapEncodeLength(p,vlen);
286 *p++ = vempty;
287 memcpy(p,val,vlen);
288 return zm;
289 }
290
291 /* Remove the specified key. If 'deleted' is not NULL the pointed integer is
292 * set to 0 if the key was not found, to 1 if it was found and deleted. */
293 unsigned char *zipmapDel(unsigned char *zm, unsigned char *key, unsigned int klen, int *deleted) {
294 unsigned int zmlen, freelen;
295 unsigned char *p = zipmapLookupRaw(zm,key,klen,&zmlen);
296 if (p) {
297 freelen = zipmapRawEntryLength(p);
298 memmove(p, p+freelen, zmlen-((p-zm)+freelen+1));
299 zm = zipmapResize(zm, zmlen-freelen);
300
301 /* Decrease zipmap length */
302 if (zm[0] < ZIPMAP_BIGLEN) zm[0]--;
303
304 if (deleted) *deleted = 1;
305 } else {
306 if (deleted) *deleted = 0;
307 }
308 return zm;
309 }
310
311 /* Call it before to iterate trought elements via zipmapNext() */
312 unsigned char *zipmapRewind(unsigned char *zm) {
313 return zm+1;
314 }
315
316 /* This function is used to iterate through all the zipmap elements.
317 * In the first call the first argument is the pointer to the zipmap + 1.
318 * In the next calls what zipmapNext returns is used as first argument.
319 * Example:
320 *
321 * unsigned char *i = zipmapRewind(my_zipmap);
322 * while((i = zipmapNext(i,&key,&klen,&value,&vlen)) != NULL) {
323 * printf("%d bytes key at $p\n", klen, key);
324 * printf("%d bytes value at $p\n", vlen, value);
325 * }
326 */
327 unsigned char *zipmapNext(unsigned char *zm, unsigned char **key, unsigned int *klen, unsigned char **value, unsigned int *vlen) {
328 while(zm[0] == ZIPMAP_EMPTY)
329 zm += zipmapDecodeLength(zm+1);
330 if (zm[0] == ZIPMAP_END) return NULL;
331 if (key) {
332 *key = zm;
333 *klen = zipmapDecodeLength(zm);
334 *key += ZIPMAP_LEN_BYTES(*klen);
335 }
336 zm += zipmapRawKeyLength(zm);
337 if (value) {
338 *value = zm+1;
339 *vlen = zipmapDecodeLength(zm);
340 *value += ZIPMAP_LEN_BYTES(*vlen);
341 }
342 zm += zipmapRawValueLength(zm);
343 return zm;
344 }
345
346 /* Search a key and retrieve the pointer and len of the associated value.
347 * If the key is found the function returns 1, otherwise 0. */
348 int zipmapGet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char **value, unsigned int *vlen) {
349 unsigned char *p;
350
351 if ((p = zipmapLookupRaw(zm,key,klen,NULL)) == NULL) return 0;
352 p += zipmapRawKeyLength(p);
353 *vlen = zipmapDecodeLength(p);
354 *value = p + ZIPMAP_LEN_BYTES(*vlen) + 1;
355 return 1;
356 }
357
358 /* Return 1 if the key exists, otherwise 0 is returned. */
359 int zipmapExists(unsigned char *zm, unsigned char *key, unsigned int klen) {
360 return zipmapLookupRaw(zm,key,klen,NULL) != NULL;
361 }
362
363 /* Return the number of entries inside a zipmap */
364 unsigned int zipmapLen(unsigned char *zm) {
365 unsigned int len = 0;
366 if (zm[0] < ZIPMAP_BIGLEN) {
367 len = zm[0];
368 } else {
369 unsigned char *p = zipmapRewind(zm);
370 while((p = zipmapNext(p,NULL,NULL,NULL,NULL)) != NULL) len++;
371
372 /* Re-store length if small enough */
373 if (len < ZIPMAP_BIGLEN) zm[0] = len;
374 }
375 return len;
376 }
377
378 void zipmapRepr(unsigned char *p) {
379 unsigned int l;
380
381 printf("{status %u}",*p++);
382 while(1) {
383 if (p[0] == ZIPMAP_END) {
384 printf("{end}");
385 break;
386 } else if (p[0] == ZIPMAP_EMPTY) {
387 l = zipmapDecodeLength(p+1);
388 printf("{%u empty block}", l);
389 p += l;
390 } else {
391 unsigned char e;
392
393 l = zipmapDecodeLength(p);
394 printf("{key %u}",l);
395 p += zipmapEncodeLength(NULL,l);
396 fwrite(p,l,1,stdout);
397 p += l;
398
399 l = zipmapDecodeLength(p);
400 printf("{value %u}",l);
401 p += zipmapEncodeLength(NULL,l);
402 e = *p++;
403 fwrite(p,l,1,stdout);
404 p += l+e;
405 if (e) {
406 printf("[");
407 while(e--) printf(".");
408 printf("]");
409 }
410 }
411 }
412 printf("\n");
413 }
414
415 #ifdef ZIPMAP_TEST_MAIN
416 int main(void) {
417 unsigned char *zm;
418
419 zm = zipmapNew();
420
421 zm = zipmapSet(zm,(unsigned char*) "name",4, (unsigned char*) "foo",3,NULL);
422 zm = zipmapSet(zm,(unsigned char*) "surname",7, (unsigned char*) "foo",3,NULL);
423 zm = zipmapSet(zm,(unsigned char*) "age",3, (unsigned char*) "foo",3,NULL);
424 zipmapRepr(zm);
425 exit(1);
426
427 zm = zipmapSet(zm,(unsigned char*) "hello",5, (unsigned char*) "world!",6,NULL);
428 zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "bar",3,NULL);
429 zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "!",1,NULL);
430 zipmapRepr(zm);
431 zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "12345",5,NULL);
432 zipmapRepr(zm);
433 zm = zipmapSet(zm,(unsigned char*) "new",3, (unsigned char*) "xx",2,NULL);
434 zm = zipmapSet(zm,(unsigned char*) "noval",5, (unsigned char*) "",0,NULL);
435 zipmapRepr(zm);
436 zm = zipmapDel(zm,(unsigned char*) "new",3,NULL);
437 zipmapRepr(zm);
438 printf("\nPerform a direct lookup:\n");
439 {
440 unsigned char *value;
441 unsigned int vlen;
442
443 if (zipmapGet(zm,(unsigned char*) "foo",3,&value,&vlen)) {
444 printf(" foo is associated to the %d bytes value: %.*s\n",
445 vlen, vlen, value);
446 }
447 }
448 printf("\nIterate trought elements:\n");
449 {
450 unsigned char *i = zipmapRewind(zm);
451 unsigned char *key, *value;
452 unsigned int klen, vlen;
453
454 while((i = zipmapNext(i,&key,&klen,&value,&vlen)) != NULL) {
455 printf(" %d:%.*s => %d:%.*s\n", klen, klen, key, vlen, vlen, value);
456 }
457 }
458 return 0;
459 }
460 #endif