aboutsummaryrefslogtreecommitdiff
path: root/examples/redis-unstable/src/zipmap.c
diff options
context:
space:
mode:
Diffstat (limited to 'examples/redis-unstable/src/zipmap.c')
-rw-r--r--examples/redis-unstable/src/zipmap.c524
1 files changed, 524 insertions, 0 deletions
diff --git a/examples/redis-unstable/src/zipmap.c b/examples/redis-unstable/src/zipmap.c
new file mode 100644
index 0000000..51c64ca
--- /dev/null
+++ b/examples/redis-unstable/src/zipmap.c
@@ -0,0 +1,524 @@
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 a 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-Present, Redis Ltd.
16 * All rights reserved.
17 *
18 * Licensed under your choice of (a) the Redis Source Available License 2.0
19 * (RSALv2); or (b) the Server Side Public License v1 (SSPLv1); or (c) the
20 * GNU Affero General Public License v3 (AGPLv3).
21 */
22
23/* Memory layout of a zipmap, for the map "foo" => "bar", "hello" => "world":
24 *
25 * <zmlen><len>"foo"<len><free>"bar"<len>"hello"<len><free>"world"
26 *
27 * <zmlen> is 1 byte length that holds the current size of the zipmap.
28 * When the zipmap length is greater than or equal to 254, this value
29 * is not used and the zipmap needs to be traversed to find out the length.
30 *
31 * <len> is the length of the following string (key or value).
32 * <len> lengths are encoded in a single value or in a 5 bytes value.
33 * If the first byte value (as an unsigned 8 bit value) is between 0 and
34 * 253, it's a single-byte length. If it is 254 then a four bytes unsigned
35 * integer follows (in the host byte ordering). A value of 255 is used to
36 * signal the end of the hash.
37 *
38 * <free> is the number of free unused bytes after the string, resulting
39 * from modification of values associated to a key. For instance if "foo"
40 * is set to "bar", and later "foo" will be set to "hi", it will have a
41 * free byte to use if the value will enlarge again later, or even in
42 * order to add a key/value pair if it fits.
43 *
44 * <free> is always an unsigned 8 bit number, because if after an
45 * update operation there are more than a few free bytes, the zipmap will be
46 * reallocated to make sure it is as small as possible.
47 *
48 * The most compact representation of the above two elements hash is actually:
49 *
50 * "\x02\x03foo\x03\x00bar\x05hello\x05\x00world\xff"
51 *
52 * Note that because keys and values are prefixed length "objects",
53 * the lookup will take O(N) where N is the number of elements
54 * in the zipmap and *not* the number of bytes needed to represent the zipmap.
55 * This lowers the constant times considerably.
56 */
57
58#include <stdio.h>
59#include <string.h>
60#include <assert.h>
61#include "zmalloc.h"
62#include "endianconv.h"
63
64#define ZIPMAP_BIGLEN 254
65#define ZIPMAP_END 255
66
67/* The following defines the max value for the <free> field described in the
68 * comments above, that is, the max number of trailing bytes in a value. */
69#define ZIPMAP_VALUE_MAX_FREE 4
70
71/* The following macro returns the number of bytes needed to encode the length
72 * for the integer value _l, that is, 1 byte for lengths < ZIPMAP_BIGLEN and
73 * 5 bytes for all the other lengths. */
74#define ZIPMAP_LEN_BYTES(_l) (((_l) < ZIPMAP_BIGLEN) ? 1 : sizeof(unsigned int)+1)
75
76/* Create a new empty zipmap. */
77unsigned char *zipmapNew(void) {
78 unsigned char *zm = zmalloc(2);
79
80 zm[0] = 0; /* Length */
81 zm[1] = ZIPMAP_END;
82 return zm;
83}
84
85/* Decode the encoded length pointed by 'p' */
86static unsigned int zipmapDecodeLength(unsigned char *p) {
87 unsigned int len = *p;
88
89 if (len < ZIPMAP_BIGLEN) return len;
90 memcpy(&len,p+1,sizeof(unsigned int));
91 memrev32ifbe(&len);
92 return len;
93}
94
95static unsigned int zipmapGetEncodedLengthSize(unsigned char *p) {
96 return (*p < ZIPMAP_BIGLEN) ? 1: 5;
97}
98
99/* Encode the length 'l' writing it in 'p'. If p is NULL it just returns
100 * the amount of bytes required to encode such a length. */
101static unsigned int zipmapEncodeLength(unsigned char *p, unsigned int len) {
102 if (p == NULL) {
103 return ZIPMAP_LEN_BYTES(len);
104 } else {
105 if (len < ZIPMAP_BIGLEN) {
106 p[0] = len;
107 return 1;
108 } else {
109 p[0] = ZIPMAP_BIGLEN;
110 memcpy(p+1,&len,sizeof(len));
111 memrev32ifbe(p+1);
112 return 1+sizeof(len);
113 }
114 }
115}
116
117/* Search for a matching key, returning a pointer to the entry inside the
118 * zipmap. Returns NULL if the key is not found.
119 *
120 * If NULL is returned, and totlen is not NULL, it is set to the entire
121 * size of the zipmap, so that the calling function will be able to
122 * reallocate the original zipmap to make room for more entries. */
123static unsigned char *zipmapLookupRaw(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned int *totlen) {
124 unsigned char *p = zm+1, *k = NULL;
125 unsigned int l,llen;
126
127 while(*p != ZIPMAP_END) {
128 unsigned char free;
129
130 /* Match or skip the key */
131 l = zipmapDecodeLength(p);
132 llen = zipmapEncodeLength(NULL,l);
133 if (key != NULL && k == NULL && l == klen && !memcmp(p+llen,key,l)) {
134 /* Only return when the user doesn't care
135 * for the total length of the zipmap. */
136 if (totlen != NULL) {
137 k = p;
138 } else {
139 return p;
140 }
141 }
142 p += llen+l;
143 /* Skip the value as well */
144 l = zipmapDecodeLength(p);
145 p += zipmapEncodeLength(NULL,l);
146 free = p[0];
147 p += l+1+free; /* +1 to skip the free byte */
148 }
149 if (totlen != NULL) *totlen = (unsigned int)(p-zm)+1;
150 return k;
151}
152
153static unsigned long zipmapRequiredLength(unsigned int klen, unsigned int vlen) {
154 unsigned int l;
155
156 l = klen+vlen+3;
157 if (klen >= ZIPMAP_BIGLEN) l += 4;
158 if (vlen >= ZIPMAP_BIGLEN) l += 4;
159 return l;
160}
161
162/* Return the total amount used by a key (encoded length + payload) */
163static unsigned int zipmapRawKeyLength(unsigned char *p) {
164 unsigned int l = zipmapDecodeLength(p);
165 return zipmapEncodeLength(NULL,l) + l;
166}
167
168/* Return the total amount used by a value
169 * (encoded length + single byte free count + payload) */
170static unsigned int zipmapRawValueLength(unsigned char *p) {
171 unsigned int l = zipmapDecodeLength(p);
172 unsigned int used;
173
174 used = zipmapEncodeLength(NULL,l);
175 used += p[used] + 1 + l;
176 return used;
177}
178
179/* If 'p' points to a key, this function returns the total amount of
180 * bytes used to store this entry (entry = key + associated value + trailing
181 * free space if any). */
182static unsigned int zipmapRawEntryLength(unsigned char *p) {
183 unsigned int l = zipmapRawKeyLength(p);
184 return l + zipmapRawValueLength(p+l);
185}
186
187static inline unsigned char *zipmapResize(unsigned char *zm, unsigned int len) {
188 zm = zrealloc(zm, len);
189 zm[len-1] = ZIPMAP_END;
190 return zm;
191}
192
193/* Set key to value, creating the key if it does not already exist.
194 * If 'update' is not NULL, *update is set to 1 if the key was
195 * already preset, otherwise to 0. */
196unsigned char *zipmapSet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char *val, unsigned int vlen, int *update) {
197 unsigned int zmlen, offset;
198 unsigned int freelen, reqlen = zipmapRequiredLength(klen,vlen);
199 unsigned int empty, vempty;
200 unsigned char *p;
201
202 freelen = reqlen;
203 if (update) *update = 0;
204 p = zipmapLookupRaw(zm,key,klen,&zmlen);
205 if (p == NULL) {
206 /* Key not found: enlarge */
207 zm = zipmapResize(zm, zmlen+reqlen);
208 p = zm+zmlen-1;
209 zmlen = zmlen+reqlen;
210
211 /* Increase zipmap length (this is an insert) */
212 if (zm[0] < ZIPMAP_BIGLEN) zm[0]++;
213 } else {
214 /* Key found. Is there enough space for the new value? */
215 /* Compute the total length: */
216 if (update) *update = 1;
217 freelen = zipmapRawEntryLength(p);
218 if (freelen < reqlen) {
219 /* Store the offset of this key within the current zipmap, so
220 * it can be resized. Then, move the tail backwards so this
221 * pair fits at the current position. */
222 offset = p-zm;
223 zm = zipmapResize(zm, zmlen-freelen+reqlen);
224 p = zm+offset;
225
226 /* The +1 in the number of bytes to be moved is caused by the
227 * end-of-zipmap byte. Note: the *original* zmlen is used. */
228 memmove(p+reqlen, p+freelen, zmlen-(offset+freelen+1));
229 zmlen = zmlen-freelen+reqlen;
230 freelen = reqlen;
231 }
232 }
233
234 /* We now have a suitable block where the key/value entry can
235 * be written. If there is too much free space, move the tail
236 * of the zipmap a few bytes to the front and shrink the zipmap,
237 * as we want zipmaps to be very space efficient. */
238 empty = freelen-reqlen;
239 if (empty >= ZIPMAP_VALUE_MAX_FREE) {
240 /* First, move the tail <empty> bytes to the front, then resize
241 * the zipmap to be <empty> bytes smaller. */
242 offset = p-zm;
243 memmove(p+reqlen, p+freelen, zmlen-(offset+freelen+1));
244 zmlen -= empty;
245 zm = zipmapResize(zm, zmlen);
246 p = zm+offset;
247 vempty = 0;
248 } else {
249 vempty = empty;
250 }
251
252 /* Just write the key + value and we are done. */
253 /* Key: */
254 p += zipmapEncodeLength(p,klen);
255 assert(klen < freelen);
256 memcpy(p,key,klen);
257 p += klen;
258 /* Value: */
259 p += zipmapEncodeLength(p,vlen);
260 *p++ = vempty;
261 memcpy(p,val,vlen);
262 return zm;
263}
264
265/* Remove the specified key. If 'deleted' is not NULL the pointed integer is
266 * set to 0 if the key was not found, to 1 if it was found and deleted. */
267unsigned char *zipmapDel(unsigned char *zm, unsigned char *key, unsigned int klen, int *deleted) {
268 unsigned int zmlen, freelen;
269 unsigned char *p = zipmapLookupRaw(zm,key,klen,&zmlen);
270 if (p) {
271 freelen = zipmapRawEntryLength(p);
272 memmove(p, p+freelen, zmlen-((p-zm)+freelen+1));
273 zm = zipmapResize(zm, zmlen-freelen);
274
275 /* Decrease zipmap length */
276 if (zm[0] < ZIPMAP_BIGLEN) zm[0]--;
277
278 if (deleted) *deleted = 1;
279 } else {
280 if (deleted) *deleted = 0;
281 }
282 return zm;
283}
284
285/* Call before iterating through elements via zipmapNext() */
286unsigned char *zipmapRewind(unsigned char *zm) {
287 return zm+1;
288}
289
290/* This function is used to iterate through all the zipmap elements.
291 * In the first call the first argument is the pointer to the zipmap + 1.
292 * In the next calls what zipmapNext returns is used as first argument.
293 * Example:
294 *
295 * unsigned char *i = zipmapRewind(my_zipmap);
296 * while((i = zipmapNext(i,&key,&klen,&value,&vlen)) != NULL) {
297 * printf("%d bytes key at $p\n", klen, key);
298 * printf("%d bytes value at $p\n", vlen, value);
299 * }
300 */
301unsigned char *zipmapNext(unsigned char *zm, unsigned char **key, unsigned int *klen, unsigned char **value, unsigned int *vlen) {
302 if (zm[0] == ZIPMAP_END) return NULL;
303 if (key) {
304 *key = zm;
305 *klen = zipmapDecodeLength(zm);
306 *key += ZIPMAP_LEN_BYTES(*klen);
307 }
308 zm += zipmapRawKeyLength(zm);
309 if (value) {
310 *value = zm+1;
311 *vlen = zipmapDecodeLength(zm);
312 *value += ZIPMAP_LEN_BYTES(*vlen);
313 }
314 zm += zipmapRawValueLength(zm);
315 return zm;
316}
317
318/* Search a key and retrieve the pointer and len of the associated value.
319 * If the key is found the function returns 1, otherwise 0. */
320int zipmapGet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char **value, unsigned int *vlen) {
321 unsigned char *p;
322
323 if ((p = zipmapLookupRaw(zm,key,klen,NULL)) == NULL) return 0;
324 p += zipmapRawKeyLength(p);
325 *vlen = zipmapDecodeLength(p);
326 *value = p + ZIPMAP_LEN_BYTES(*vlen) + 1;
327 return 1;
328}
329
330/* Return 1 if the key exists, otherwise 0 is returned. */
331int zipmapExists(unsigned char *zm, unsigned char *key, unsigned int klen) {
332 return zipmapLookupRaw(zm,key,klen,NULL) != NULL;
333}
334
335/* Return the number of entries inside a zipmap */
336unsigned int zipmapLen(unsigned char *zm) {
337 unsigned int len = 0;
338 if (zm[0] < ZIPMAP_BIGLEN) {
339 len = zm[0];
340 } else {
341 unsigned char *p = zipmapRewind(zm);
342 while((p = zipmapNext(p,NULL,NULL,NULL,NULL)) != NULL) len++;
343
344 /* Re-store length if small enough */
345 if (len < ZIPMAP_BIGLEN) zm[0] = len;
346 }
347 return len;
348}
349
350/* Return the raw size in bytes of a zipmap, so that we can serialize
351 * the zipmap on disk (or everywhere is needed) just writing the returned
352 * amount of bytes of the C array starting at the zipmap pointer. */
353size_t zipmapBlobLen(unsigned char *zm) {
354 unsigned int totlen;
355 zipmapLookupRaw(zm,NULL,0,&totlen);
356 return totlen;
357}
358
359/* Validate the integrity of the data structure.
360 * when `deep` is 0, only the integrity of the header is validated.
361 * when `deep` is 1, we scan all the entries one by one. */
362int zipmapValidateIntegrity(unsigned char *zm, size_t size, int deep) {
363#define OUT_OF_RANGE(p) ( \
364 (p) < zm + 2 || \
365 (p) > zm + size - 1)
366 unsigned int l, s, e;
367
368 /* check that we can actually read the header (or ZIPMAP_END). */
369 if (size < 2)
370 return 0;
371
372 /* the last byte must be the terminator. */
373 if (zm[size-1] != ZIPMAP_END)
374 return 0;
375
376 if (!deep)
377 return 1;
378
379 unsigned int count = 0;
380 unsigned char *p = zm + 1; /* skip the count */
381 while(*p != ZIPMAP_END) {
382 /* read the field name length encoding type */
383 s = zipmapGetEncodedLengthSize(p);
384 /* make sure the entry length doesn't reach outside the edge of the zipmap */
385 if (OUT_OF_RANGE(p+s))
386 return 0;
387
388 /* read the field name length */
389 l = zipmapDecodeLength(p);
390 p += s; /* skip the encoded field size */
391 p += l; /* skip the field */
392
393 /* make sure the entry doesn't reach outside the edge of the zipmap */
394 if (OUT_OF_RANGE(p))
395 return 0;
396
397 /* read the value length encoding type */
398 s = zipmapGetEncodedLengthSize(p);
399 /* make sure the entry length doesn't reach outside the edge of the zipmap */
400 if (OUT_OF_RANGE(p+s))
401 return 0;
402
403 /* read the value length */
404 l = zipmapDecodeLength(p);
405 p += s; /* skip the encoded value size*/
406 e = *p++; /* skip the encoded free space (always encoded in one byte) */
407 p += l+e; /* skip the value and free space */
408 count++;
409
410 /* make sure the entry doesn't reach outside the edge of the zipmap */
411 if (OUT_OF_RANGE(p))
412 return 0;
413 }
414
415 /* check that the zipmap is not empty. */
416 if (count == 0) return 0;
417
418 /* check that the count in the header is correct */
419 if (zm[0] != ZIPMAP_BIGLEN && zm[0] != count)
420 return 0;
421
422 return 1;
423#undef OUT_OF_RANGE
424}
425
426#ifdef REDIS_TEST
427static void zipmapRepr(unsigned char *p) {
428 unsigned int l;
429
430 printf("{status %u}",*p++);
431 while(1) {
432 if (p[0] == ZIPMAP_END) {
433 printf("{end}");
434 break;
435 } else {
436 unsigned char e;
437
438 l = zipmapDecodeLength(p);
439 printf("{key %u}",l);
440 p += zipmapEncodeLength(NULL,l);
441 if (l != 0 && fwrite(p,l,1,stdout) == 0) perror("fwrite");
442 p += l;
443
444 l = zipmapDecodeLength(p);
445 printf("{value %u}",l);
446 p += zipmapEncodeLength(NULL,l);
447 e = *p++;
448 if (l != 0 && fwrite(p,l,1,stdout) == 0) perror("fwrite");
449 p += l+e;
450 if (e) {
451 printf("[");
452 while(e--) printf(".");
453 printf("]");
454 }
455 }
456 }
457 printf("\n");
458}
459
460#define UNUSED(x) (void)(x)
461int zipmapTest(int argc, char *argv[], int flags) {
462 unsigned char *zm;
463
464 UNUSED(argc);
465 UNUSED(argv);
466 UNUSED(flags);
467
468 zm = zipmapNew();
469
470 zm = zipmapSet(zm,(unsigned char*) "name",4, (unsigned char*) "foo",3,NULL);
471 zm = zipmapSet(zm,(unsigned char*) "surname",7, (unsigned char*) "foo",3,NULL);
472 zm = zipmapSet(zm,(unsigned char*) "age",3, (unsigned char*) "foo",3,NULL);
473 zipmapRepr(zm);
474
475 zm = zipmapSet(zm,(unsigned char*) "hello",5, (unsigned char*) "world!",6,NULL);
476 zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "bar",3,NULL);
477 zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "!",1,NULL);
478 zipmapRepr(zm);
479 zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "12345",5,NULL);
480 zipmapRepr(zm);
481 zm = zipmapSet(zm,(unsigned char*) "new",3, (unsigned char*) "xx",2,NULL);
482 zm = zipmapSet(zm,(unsigned char*) "noval",5, (unsigned char*) "",0,NULL);
483 zipmapRepr(zm);
484 zm = zipmapDel(zm,(unsigned char*) "new",3,NULL);
485 zipmapRepr(zm);
486
487 printf("\nLook up large key:\n");
488 {
489 unsigned char buf[512];
490 unsigned char *value;
491 unsigned int vlen, i;
492 for (i = 0; i < 512; i++) buf[i] = 'a';
493
494 zm = zipmapSet(zm,buf,512,(unsigned char*) "long",4,NULL);
495 if (zipmapGet(zm,buf,512,&value,&vlen)) {
496 printf(" <long key> is associated to the %d bytes value: %.*s\n",
497 vlen, vlen, value);
498 }
499 }
500
501 printf("\nPerform a direct lookup:\n");
502 {
503 unsigned char *value;
504 unsigned int vlen;
505
506 if (zipmapGet(zm,(unsigned char*) "foo",3,&value,&vlen)) {
507 printf(" foo is associated to the %d bytes value: %.*s\n",
508 vlen, vlen, value);
509 }
510 }
511 printf("\nIterate through elements:\n");
512 {
513 unsigned char *i = zipmapRewind(zm);
514 unsigned char *key, *value;
515 unsigned int klen, vlen;
516
517 while((i = zipmapNext(i,&key,&klen,&value,&vlen)) != NULL) {
518 printf(" %d:%.*s => %d:%.*s\n", klen, klen, key, vlen, vlen, value);
519 }
520 }
521 zfree(zm);
522 return 0;
523}
524#endif