]> git.saurik.com Git - redis.git/blame - zipmap.c
removed references in code to ZIPMAP_EMPTY
[redis.git] / zipmap.c
CommitLineData
eb46f4bd 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 *
be0af2f0 70 * "\x00\x03foo\x03\x00bar\x05hello\x05\x00world\xff"
eb46f4bd 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 *
be0af2f0 77 * "\x00\xfd\x10........\x05hello\x05\x00world\xff"
eb46f4bd 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
38192079 90#define ZIPMAP_BIGLEN 254
eb46f4bd 91#define ZIPMAP_END 255
92
eb46f4bd 93/* The following defines the max value for the <free> field described in the
94 * comments above, that is, the max number of trailing bytes in a value. */
95#define ZIPMAP_VALUE_MAX_FREE 5
96
5234952b 97/* The following macro returns the number of bytes needed to encode the length
98 * for the integer value _l, that is, 1 byte for lengths < ZIPMAP_BIGLEN and
99 * 5 bytes for all the other lengths. */
100#define ZIPMAP_LEN_BYTES(_l) (((_l) < ZIPMAP_BIGLEN) ? 1 : sizeof(unsigned int)+1)
101
eb46f4bd 102/* Create a new empty zipmap. */
103unsigned char *zipmapNew(void) {
104 unsigned char *zm = zmalloc(2);
105
9e071b4b 106 zm[0] = 0; /* Length */
eb46f4bd 107 zm[1] = ZIPMAP_END;
108 return zm;
109}
110
111/* Decode the encoded length pointed by 'p' */
112static unsigned int zipmapDecodeLength(unsigned char *p) {
113 unsigned int len = *p;
114
115 if (len < ZIPMAP_BIGLEN) return len;
ad6de43c 116 memcpy(&len,p+1,sizeof(unsigned int));
eb46f4bd 117 return len;
118}
119
120/* Encode the length 'l' writing it in 'p'. If p is NULL it just returns
121 * the amount of bytes required to encode such a length. */
122static unsigned int zipmapEncodeLength(unsigned char *p, unsigned int len) {
123 if (p == NULL) {
5234952b 124 return ZIPMAP_LEN_BYTES(len);
eb46f4bd 125 } else {
126 if (len < ZIPMAP_BIGLEN) {
127 p[0] = len;
128 return 1;
129 } else {
130 p[0] = ZIPMAP_BIGLEN;
131 memcpy(p+1,&len,sizeof(len));
132 return 1+sizeof(len);
133 }
134 }
135}
136
137/* Search for a matching key, returning a pointer to the entry inside the
138 * zipmap. Returns NULL if the key is not found.
139 *
140 * If NULL is returned, and totlen is not NULL, it is set to the entire
141 * size of the zimap, so that the calling function will be able to
38192079 142 * reallocate the original zipmap to make room for more entries. */
43078ff8
PN
143static unsigned char *zipmapLookupRaw(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned int *totlen) {
144 unsigned char *p = zm+1, *k = NULL;
eb46f4bd 145 unsigned int l;
eb46f4bd 146
eb46f4bd 147 while(*p != ZIPMAP_END) {
43078ff8
PN
148 unsigned char free;
149
150 /* Match or skip the key */
151 l = zipmapDecodeLength(p);
152 if (k == NULL && l == klen && !memcmp(p+1,key,l)) {
153 /* Only return when the user doesn't care
154 * for the total length of the zipmap. */
155 if (totlen != NULL) {
156 k = p;
157 } else {
158 return p;
eb46f4bd 159 }
eb46f4bd 160 }
43078ff8
PN
161 p += zipmapEncodeLength(NULL,l) + l;
162 /* Skip the value as well */
163 l = zipmapDecodeLength(p);
164 p += zipmapEncodeLength(NULL,l);
165 free = p[0];
166 p += l+1+free; /* +1 to skip the free byte */
eb46f4bd 167 }
168 if (totlen != NULL) *totlen = (unsigned int)(p-zm)+1;
43078ff8 169 return k;
eb46f4bd 170}
171
172static unsigned long zipmapRequiredLength(unsigned int klen, unsigned int vlen) {
173 unsigned int l;
174
175 l = klen+vlen+3;
176 if (klen >= ZIPMAP_BIGLEN) l += 4;
177 if (vlen >= ZIPMAP_BIGLEN) l += 4;
178 return l;
179}
180
8ec08321 181/* Return the total amount used by a key (encoded length + payload) */
eb46f4bd 182static unsigned int zipmapRawKeyLength(unsigned char *p) {
183 unsigned int l = zipmapDecodeLength(p);
184
185 return zipmapEncodeLength(NULL,l) + l;
186}
187
8ec08321 188/* Return the total amount used by a value
eb46f4bd 189 * (encoded length + single byte free count + payload) */
190static unsigned int zipmapRawValueLength(unsigned char *p) {
191 unsigned int l = zipmapDecodeLength(p);
192 unsigned int used;
193
194 used = zipmapEncodeLength(NULL,l);
195 used += p[used] + 1 + l;
196 return used;
197}
198
cd5a96ee 199/* If 'p' points to a key, this function returns the total amount of
200 * bytes used to store this entry (entry = key + associated value + trailing
201 * free space if any). */
202static unsigned int zipmapRawEntryLength(unsigned char *p) {
203 unsigned int l = zipmapRawKeyLength(p);
204
205 return l + zipmapRawValueLength(p+l);
206}
207
43078ff8
PN
208static inline unsigned char *zipmapResize(unsigned char *zm, unsigned int len) {
209 zm = zrealloc(zm, len);
210 zm[len-1] = ZIPMAP_END;
211 return zm;
212}
213
5234952b 214/* Set key to value, creating the key if it does not already exist.
215 * If 'update' is not NULL, *update is set to 1 if the key was
216 * already preset, otherwise to 0. */
217unsigned char *zipmapSet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char *val, unsigned int vlen, int *update) {
43078ff8
PN
218 unsigned int zmlen;
219 unsigned int freelen, reqlen = zipmapRequiredLength(klen,vlen);
eb46f4bd 220 unsigned int empty, vempty;
221 unsigned char *p;
222
223 freelen = reqlen;
5234952b 224 if (update) *update = 0;
43078ff8
PN
225 p = zipmapLookupRaw(zm,key,klen,&zmlen);
226 if (p == NULL) {
227 /* Key not found: enlarge */
228 zm = zipmapResize(zm, zmlen+reqlen);
229 p = zm+zmlen-1;
230 zmlen = zmlen+reqlen;
9e071b4b
PN
231
232 /* Increase zipmap length (this is an insert) */
233 if (zm[0] < ZIPMAP_BIGLEN) zm[0]++;
eb46f4bd 234 } else {
235 unsigned char *b = p;
236
237 /* Key found. Is there enough space for the new value? */
238 /* Compute the total length: */
5234952b 239 if (update) *update = 1;
eb46f4bd 240 freelen = zipmapRawKeyLength(b);
241 b += freelen;
242 freelen += zipmapRawValueLength(b);
243 if (freelen < reqlen) {
43078ff8
PN
244 /* Move remaining entries to the current position, so this
245 * pair can be appended. Note: the +1 in memmove is caused
246 * by the end-of-zipmap byte. */
247 memmove(p, p+freelen, zmlen-((p-zm)+freelen+1));
248 zm = zipmapResize(zm, zmlen-freelen+reqlen);
249 p = zm+zmlen-1-freelen;
250 zmlen = zmlen-1-freelen+reqlen;
251 freelen = reqlen;
eb46f4bd 252 }
253 }
254
255 /* Ok we have a suitable block where to write the new key/value
256 * entry. */
257 empty = freelen-reqlen;
258 /* If there is too much free space mark it as a free block instead
259 * of adding it as trailing empty space for the value, as we want
260 * zipmaps to be very space efficient. */
43078ff8
PN
261 if (empty >= ZIPMAP_VALUE_MAX_FREE) {
262 memmove(p+reqlen, p+freelen, zmlen-((p-zm)+freelen+1));
263 zmlen -= empty;
264 zm = zipmapResize(zm, zmlen);
eb46f4bd 265 vempty = 0;
eb46f4bd 266 } else {
267 vempty = empty;
268 }
269
270 /* Just write the key + value and we are done. */
271 /* Key: */
272 p += zipmapEncodeLength(p,klen);
273 memcpy(p,key,klen);
274 p += klen;
275 /* Value: */
276 p += zipmapEncodeLength(p,vlen);
277 *p++ = vempty;
278 memcpy(p,val,vlen);
279 return zm;
280}
281
cd5a96ee 282/* Remove the specified key. If 'deleted' is not NULL the pointed integer is
283 * set to 0 if the key was not found, to 1 if it was found and deleted. */
284unsigned char *zipmapDel(unsigned char *zm, unsigned char *key, unsigned int klen, int *deleted) {
9e071b4b 285 unsigned int zmlen, freelen;
43078ff8 286 unsigned char *p = zipmapLookupRaw(zm,key,klen,&zmlen);
cd5a96ee 287 if (p) {
9e071b4b 288 freelen = zipmapRawEntryLength(p);
43078ff8
PN
289 memmove(p, p+freelen, zmlen-((p-zm)+freelen+1));
290 zm = zipmapResize(zm, zmlen-freelen);
9e071b4b
PN
291
292 /* Decrease zipmap length */
293 if (zm[0] < ZIPMAP_BIGLEN) zm[0]--;
294
cd5a96ee 295 if (deleted) *deleted = 1;
296 } else {
297 if (deleted) *deleted = 0;
298 }
299 return zm;
300}
301
5234952b 302/* Call it before to iterate trought elements via zipmapNext() */
303unsigned char *zipmapRewind(unsigned char *zm) {
304 return zm+1;
305}
306
66ef8da0 307/* This function is used to iterate through all the zipmap elements.
308 * In the first call the first argument is the pointer to the zipmap + 1.
309 * In the next calls what zipmapNext returns is used as first argument.
310 * Example:
311 *
5234952b 312 * unsigned char *i = zipmapRewind(my_zipmap);
66ef8da0 313 * while((i = zipmapNext(i,&key,&klen,&value,&vlen)) != NULL) {
314 * printf("%d bytes key at $p\n", klen, key);
315 * printf("%d bytes value at $p\n", vlen, value);
316 * }
317 */
5234952b 318unsigned char *zipmapNext(unsigned char *zm, unsigned char **key, unsigned int *klen, unsigned char **value, unsigned int *vlen) {
66ef8da0 319 if (zm[0] == ZIPMAP_END) return NULL;
320 if (key) {
321 *key = zm;
322 *klen = zipmapDecodeLength(zm);
5234952b 323 *key += ZIPMAP_LEN_BYTES(*klen);
66ef8da0 324 }
325 zm += zipmapRawKeyLength(zm);
326 if (value) {
327 *value = zm+1;
328 *vlen = zipmapDecodeLength(zm);
5234952b 329 *value += ZIPMAP_LEN_BYTES(*vlen);
66ef8da0 330 }
331 zm += zipmapRawValueLength(zm);
332 return zm;
333}
334
5234952b 335/* Search a key and retrieve the pointer and len of the associated value.
336 * If the key is found the function returns 1, otherwise 0. */
337int zipmapGet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char **value, unsigned int *vlen) {
338 unsigned char *p;
339
43078ff8 340 if ((p = zipmapLookupRaw(zm,key,klen,NULL)) == NULL) return 0;
5234952b 341 p += zipmapRawKeyLength(p);
342 *vlen = zipmapDecodeLength(p);
343 *value = p + ZIPMAP_LEN_BYTES(*vlen) + 1;
344 return 1;
345}
346
347/* Return 1 if the key exists, otherwise 0 is returned. */
348int zipmapExists(unsigned char *zm, unsigned char *key, unsigned int klen) {
43078ff8 349 return zipmapLookupRaw(zm,key,klen,NULL) != NULL;
5234952b 350}
351
b1befe6a 352/* Return the number of entries inside a zipmap */
353unsigned int zipmapLen(unsigned char *zm) {
b1befe6a 354 unsigned int len = 0;
9e071b4b
PN
355 if (zm[0] < ZIPMAP_BIGLEN) {
356 len = zm[0];
357 } else {
358 unsigned char *p = zipmapRewind(zm);
359 while((p = zipmapNext(p,NULL,NULL,NULL,NULL)) != NULL) len++;
b1befe6a 360
9e071b4b
PN
361 /* Re-store length if small enough */
362 if (len < ZIPMAP_BIGLEN) zm[0] = len;
363 }
b1befe6a 364 return len;
365}
366
eb46f4bd 367void zipmapRepr(unsigned char *p) {
368 unsigned int l;
369
370 printf("{status %u}",*p++);
371 while(1) {
372 if (p[0] == ZIPMAP_END) {
373 printf("{end}");
374 break;
eb46f4bd 375 } else {
376 unsigned char e;
377
378 l = zipmapDecodeLength(p);
379 printf("{key %u}",l);
380 p += zipmapEncodeLength(NULL,l);
381 fwrite(p,l,1,stdout);
382 p += l;
383
384 l = zipmapDecodeLength(p);
385 printf("{value %u}",l);
386 p += zipmapEncodeLength(NULL,l);
387 e = *p++;
388 fwrite(p,l,1,stdout);
8ec08321 389 p += l+e;
eb46f4bd 390 if (e) {
391 printf("[");
392 while(e--) printf(".");
393 printf("]");
394 }
395 }
396 }
397 printf("\n");
398}
399
5234952b 400#ifdef ZIPMAP_TEST_MAIN
eb46f4bd 401int main(void) {
402 unsigned char *zm;
403
404 zm = zipmapNew();
cbba7dd7 405
406 zm = zipmapSet(zm,(unsigned char*) "name",4, (unsigned char*) "foo",3,NULL);
407 zm = zipmapSet(zm,(unsigned char*) "surname",7, (unsigned char*) "foo",3,NULL);
408 zm = zipmapSet(zm,(unsigned char*) "age",3, (unsigned char*) "foo",3,NULL);
409 zipmapRepr(zm);
410 exit(1);
411
5234952b 412 zm = zipmapSet(zm,(unsigned char*) "hello",5, (unsigned char*) "world!",6,NULL);
413 zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "bar",3,NULL);
414 zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "!",1,NULL);
eb46f4bd 415 zipmapRepr(zm);
5234952b 416 zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "12345",5,NULL);
be0af2f0 417 zipmapRepr(zm);
5234952b 418 zm = zipmapSet(zm,(unsigned char*) "new",3, (unsigned char*) "xx",2,NULL);
978c2c94 419 zm = zipmapSet(zm,(unsigned char*) "noval",5, (unsigned char*) "",0,NULL);
be0af2f0 420 zipmapRepr(zm);
cd5a96ee 421 zm = zipmapDel(zm,(unsigned char*) "new",3,NULL);
422 zipmapRepr(zm);
5234952b 423 printf("\nPerform a direct lookup:\n");
424 {
425 unsigned char *value;
426 unsigned int vlen;
427
428 if (zipmapGet(zm,(unsigned char*) "foo",3,&value,&vlen)) {
429 printf(" foo is associated to the %d bytes value: %.*s\n",
430 vlen, vlen, value);
431 }
432 }
433 printf("\nIterate trought elements:\n");
66ef8da0 434 {
5234952b 435 unsigned char *i = zipmapRewind(zm);
66ef8da0 436 unsigned char *key, *value;
437 unsigned int klen, vlen;
438
439 while((i = zipmapNext(i,&key,&klen,&value,&vlen)) != NULL) {
5234952b 440 printf(" %d:%.*s => %d:%.*s\n", klen, klen, key, vlen, vlen, value);
66ef8da0 441 }
442 }
eb46f4bd 443 return 0;
444}
5234952b 445#endif