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