]> git.saurik.com Git - redis.git/blame - zipmap.c
initial work for integer encoding in ziplists
[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 *
bfded2aa 45 * <zmlen><len>"foo"<len><free>"bar"<len>"hello"<len><free>"world"
eb46f4bd 46 *
bfded2aa
PN
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.
eb46f4bd 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 fo 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
60 * after the string, resulting from modification of values associated to a
61 * key (for instance if "foo" is set to "bar', and later "foo" will be se to
62 * "hi", I'll have a free byte to use if the value will enlarge again later,
63 * or even in order to add a key/value pair if it fits.
64 *
65 * <free> is always an unsigned 8 bit number, because if after an
bfded2aa
PN
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.
eb46f4bd 68 *
69 * The most compact representation of the above two elements hash is actually:
70 *
bfded2aa 71 * "\x02\x03foo\x03\x00bar\x05hello\x05\x00world\xff"
eb46f4bd 72 *
bfded2aa
PN
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
eb46f4bd 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 <assert.h>
82#include "zmalloc.h"
3d04d29e 83#include "zip.c"
eb46f4bd 84
eb46f4bd 85/* The following defines the max value for the <free> field described in the
86 * comments above, that is, the max number of trailing bytes in a value. */
8c670072 87#define ZIPMAP_VALUE_MAX_FREE 4
eb46f4bd 88
89/* Create a new empty zipmap. */
90unsigned char *zipmapNew(void) {
91 unsigned char *zm = zmalloc(2);
92
9e071b4b 93 zm[0] = 0; /* Length */
3d04d29e 94 zm[1] = ZIP_END;
eb46f4bd 95 return zm;
96}
97
eb46f4bd 98/* Search for a matching key, returning a pointer to the entry inside the
99 * zipmap. Returns NULL if the key is not found.
100 *
101 * If NULL is returned, and totlen is not NULL, it is set to the entire
102 * size of the zimap, so that the calling function will be able to
38192079 103 * reallocate the original zipmap to make room for more entries. */
43078ff8
PN
104static unsigned char *zipmapLookupRaw(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned int *totlen) {
105 unsigned char *p = zm+1, *k = NULL;
b36d1c30 106 unsigned int l,llen;
eb46f4bd 107
3d04d29e 108 while(*p != ZIP_END) {
43078ff8
PN
109 unsigned char free;
110
111 /* Match or skip the key */
3d04d29e
PN
112 l = zipDecodeLength(p);
113 llen = zipEncodeLength(NULL,l);
b36d1c30 114 if (k == NULL && l == klen && !memcmp(p+llen,key,l)) {
43078ff8
PN
115 /* Only return when the user doesn't care
116 * for the total length of the zipmap. */
117 if (totlen != NULL) {
118 k = p;
119 } else {
120 return p;
eb46f4bd 121 }
eb46f4bd 122 }
b36d1c30 123 p += llen+l;
43078ff8 124 /* Skip the value as well */
3d04d29e
PN
125 l = zipDecodeLength(p);
126 p += zipEncodeLength(NULL,l);
43078ff8
PN
127 free = p[0];
128 p += l+1+free; /* +1 to skip the free byte */
eb46f4bd 129 }
130 if (totlen != NULL) *totlen = (unsigned int)(p-zm)+1;
43078ff8 131 return k;
eb46f4bd 132}
133
134static unsigned long zipmapRequiredLength(unsigned int klen, unsigned int vlen) {
135 unsigned int l;
136
137 l = klen+vlen+3;
3d04d29e
PN
138 if (klen >= ZIP_BIGLEN) l += 4;
139 if (vlen >= ZIP_BIGLEN) l += 4;
eb46f4bd 140 return l;
141}
142
8ec08321 143/* Return the total amount used by a key (encoded length + payload) */
eb46f4bd 144static unsigned int zipmapRawKeyLength(unsigned char *p) {
3d04d29e 145 return zipRawEntryLength(p);
eb46f4bd 146}
147
8ec08321 148/* Return the total amount used by a value
eb46f4bd 149 * (encoded length + single byte free count + payload) */
150static unsigned int zipmapRawValueLength(unsigned char *p) {
3d04d29e 151 unsigned int l = zipDecodeLength(p);
eb46f4bd 152 unsigned int used;
153
3d04d29e 154 used = zipEncodeLength(NULL,l);
eb46f4bd 155 used += p[used] + 1 + l;
156 return used;
157}
158
cd5a96ee 159/* If 'p' points to a key, this function returns the total amount of
160 * bytes used to store this entry (entry = key + associated value + trailing
161 * free space if any). */
162static unsigned int zipmapRawEntryLength(unsigned char *p) {
163 unsigned int l = zipmapRawKeyLength(p);
cd5a96ee 164 return l + zipmapRawValueLength(p+l);
165}
166
5234952b 167/* Set key to value, creating the key if it does not already exist.
168 * If 'update' is not NULL, *update is set to 1 if the key was
169 * already preset, otherwise to 0. */
170unsigned char *zipmapSet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char *val, unsigned int vlen, int *update) {
da2cfe8a 171 unsigned int zmlen, offset;
43078ff8 172 unsigned int freelen, reqlen = zipmapRequiredLength(klen,vlen);
eb46f4bd 173 unsigned int empty, vempty;
174 unsigned char *p;
175
176 freelen = reqlen;
5234952b 177 if (update) *update = 0;
43078ff8
PN
178 p = zipmapLookupRaw(zm,key,klen,&zmlen);
179 if (p == NULL) {
180 /* Key not found: enlarge */
3d04d29e 181 zm = zipResize(zm, zmlen+reqlen);
43078ff8
PN
182 p = zm+zmlen-1;
183 zmlen = zmlen+reqlen;
9e071b4b
PN
184
185 /* Increase zipmap length (this is an insert) */
3d04d29e 186 if (zm[0] < ZIP_BIGLEN) zm[0]++;
eb46f4bd 187 } else {
eb46f4bd 188 /* Key found. Is there enough space for the new value? */
189 /* Compute the total length: */
5234952b 190 if (update) *update = 1;
06278a67 191 freelen = zipmapRawEntryLength(p);
eb46f4bd 192 if (freelen < reqlen) {
da2cfe8a
PN
193 /* Store the offset of this key within the current zipmap, so
194 * it can be resized. Then, move the tail backwards so this
195 * pair fits at the current position. */
196 offset = p-zm;
3d04d29e 197 zm = zipResize(zm, zmlen-freelen+reqlen);
da2cfe8a
PN
198 p = zm+offset;
199
200 /* The +1 in the number of bytes to be moved is caused by the
201 * end-of-zipmap byte. Note: the *original* zmlen is used. */
202 memmove(p+reqlen, p+freelen, zmlen-(offset+freelen+1));
203 zmlen = zmlen-freelen+reqlen;
43078ff8 204 freelen = reqlen;
eb46f4bd 205 }
206 }
207
da2cfe8a
PN
208 /* We now have a suitable block where the key/value entry can
209 * be written. If there is too much free space, move the tail
210 * of the zipmap a few bytes to the front and shrink the zipmap,
211 * as we want zipmaps to be very space efficient. */
eb46f4bd 212 empty = freelen-reqlen;
43078ff8 213 if (empty >= ZIPMAP_VALUE_MAX_FREE) {
da2cfe8a
PN
214 /* First, move the tail <empty> bytes to the front, then resize
215 * the zipmap to be <empty> bytes smaller. */
216 offset = p-zm;
217 memmove(p+reqlen, p+freelen, zmlen-(offset+freelen+1));
43078ff8 218 zmlen -= empty;
3d04d29e 219 zm = zipResize(zm, zmlen);
da2cfe8a 220 p = zm+offset;
eb46f4bd 221 vempty = 0;
eb46f4bd 222 } else {
223 vempty = empty;
224 }
225
226 /* Just write the key + value and we are done. */
227 /* Key: */
3d04d29e 228 p += zipEncodeLength(p,klen);
eb46f4bd 229 memcpy(p,key,klen);
230 p += klen;
231 /* Value: */
3d04d29e 232 p += zipEncodeLength(p,vlen);
eb46f4bd 233 *p++ = vempty;
234 memcpy(p,val,vlen);
235 return zm;
236}
237
cd5a96ee 238/* Remove the specified key. If 'deleted' is not NULL the pointed integer is
239 * set to 0 if the key was not found, to 1 if it was found and deleted. */
240unsigned char *zipmapDel(unsigned char *zm, unsigned char *key, unsigned int klen, int *deleted) {
9e071b4b 241 unsigned int zmlen, freelen;
43078ff8 242 unsigned char *p = zipmapLookupRaw(zm,key,klen,&zmlen);
cd5a96ee 243 if (p) {
9e071b4b 244 freelen = zipmapRawEntryLength(p);
43078ff8 245 memmove(p, p+freelen, zmlen-((p-zm)+freelen+1));
3d04d29e 246 zm = zipResize(zm, zmlen-freelen);
9e071b4b
PN
247
248 /* Decrease zipmap length */
3d04d29e 249 if (zm[0] < ZIP_BIGLEN) zm[0]--;
9e071b4b 250
cd5a96ee 251 if (deleted) *deleted = 1;
252 } else {
253 if (deleted) *deleted = 0;
254 }
255 return zm;
256}
257
5234952b 258/* Call it before to iterate trought elements via zipmapNext() */
259unsigned char *zipmapRewind(unsigned char *zm) {
260 return zm+1;
261}
262
66ef8da0 263/* This function is used to iterate through all the zipmap elements.
264 * In the first call the first argument is the pointer to the zipmap + 1.
265 * In the next calls what zipmapNext returns is used as first argument.
266 * Example:
267 *
5234952b 268 * unsigned char *i = zipmapRewind(my_zipmap);
66ef8da0 269 * while((i = zipmapNext(i,&key,&klen,&value,&vlen)) != NULL) {
270 * printf("%d bytes key at $p\n", klen, key);
271 * printf("%d bytes value at $p\n", vlen, value);
272 * }
273 */
5234952b 274unsigned char *zipmapNext(unsigned char *zm, unsigned char **key, unsigned int *klen, unsigned char **value, unsigned int *vlen) {
3d04d29e 275 if (zm[0] == ZIP_END) return NULL;
66ef8da0 276 if (key) {
277 *key = zm;
3d04d29e
PN
278 *klen = zipDecodeLength(zm);
279 *key += ZIP_LEN_BYTES(*klen);
66ef8da0 280 }
281 zm += zipmapRawKeyLength(zm);
282 if (value) {
283 *value = zm+1;
3d04d29e
PN
284 *vlen = zipDecodeLength(zm);
285 *value += ZIP_LEN_BYTES(*vlen);
66ef8da0 286 }
287 zm += zipmapRawValueLength(zm);
288 return zm;
289}
290
5234952b 291/* Search a key and retrieve the pointer and len of the associated value.
292 * If the key is found the function returns 1, otherwise 0. */
293int zipmapGet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char **value, unsigned int *vlen) {
294 unsigned char *p;
295
43078ff8 296 if ((p = zipmapLookupRaw(zm,key,klen,NULL)) == NULL) return 0;
5234952b 297 p += zipmapRawKeyLength(p);
3d04d29e
PN
298 *vlen = zipDecodeLength(p);
299 *value = p + ZIP_LEN_BYTES(*vlen) + 1;
5234952b 300 return 1;
301}
302
303/* Return 1 if the key exists, otherwise 0 is returned. */
304int zipmapExists(unsigned char *zm, unsigned char *key, unsigned int klen) {
43078ff8 305 return zipmapLookupRaw(zm,key,klen,NULL) != NULL;
5234952b 306}
307
b1befe6a 308/* Return the number of entries inside a zipmap */
309unsigned int zipmapLen(unsigned char *zm) {
b1befe6a 310 unsigned int len = 0;
3d04d29e 311 if (zm[0] < ZIP_BIGLEN) {
9e071b4b
PN
312 len = zm[0];
313 } else {
314 unsigned char *p = zipmapRewind(zm);
315 while((p = zipmapNext(p,NULL,NULL,NULL,NULL)) != NULL) len++;
b1befe6a 316
9e071b4b 317 /* Re-store length if small enough */
3d04d29e 318 if (len < ZIP_BIGLEN) zm[0] = len;
9e071b4b 319 }
b1befe6a 320 return len;
321}
322
eb46f4bd 323void zipmapRepr(unsigned char *p) {
324 unsigned int l;
325
326 printf("{status %u}",*p++);
327 while(1) {
3d04d29e 328 if (p[0] == ZIP_END) {
eb46f4bd 329 printf("{end}");
330 break;
eb46f4bd 331 } else {
332 unsigned char e;
333
3d04d29e 334 l = zipDecodeLength(p);
eb46f4bd 335 printf("{key %u}",l);
3d04d29e 336 p += zipEncodeLength(NULL,l);
eb46f4bd 337 fwrite(p,l,1,stdout);
338 p += l;
339
3d04d29e 340 l = zipDecodeLength(p);
eb46f4bd 341 printf("{value %u}",l);
3d04d29e 342 p += zipEncodeLength(NULL,l);
eb46f4bd 343 e = *p++;
344 fwrite(p,l,1,stdout);
8ec08321 345 p += l+e;
eb46f4bd 346 if (e) {
347 printf("[");
348 while(e--) printf(".");
349 printf("]");
350 }
351 }
352 }
353 printf("\n");
354}
355
5234952b 356#ifdef ZIPMAP_TEST_MAIN
eb46f4bd 357int main(void) {
358 unsigned char *zm;
359
360 zm = zipmapNew();
cbba7dd7 361
362 zm = zipmapSet(zm,(unsigned char*) "name",4, (unsigned char*) "foo",3,NULL);
363 zm = zipmapSet(zm,(unsigned char*) "surname",7, (unsigned char*) "foo",3,NULL);
364 zm = zipmapSet(zm,(unsigned char*) "age",3, (unsigned char*) "foo",3,NULL);
365 zipmapRepr(zm);
cbba7dd7 366
5234952b 367 zm = zipmapSet(zm,(unsigned char*) "hello",5, (unsigned char*) "world!",6,NULL);
368 zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "bar",3,NULL);
369 zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "!",1,NULL);
eb46f4bd 370 zipmapRepr(zm);
5234952b 371 zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "12345",5,NULL);
be0af2f0 372 zipmapRepr(zm);
5234952b 373 zm = zipmapSet(zm,(unsigned char*) "new",3, (unsigned char*) "xx",2,NULL);
978c2c94 374 zm = zipmapSet(zm,(unsigned char*) "noval",5, (unsigned char*) "",0,NULL);
be0af2f0 375 zipmapRepr(zm);
cd5a96ee 376 zm = zipmapDel(zm,(unsigned char*) "new",3,NULL);
377 zipmapRepr(zm);
b36d1c30
PN
378
379 printf("\nLook up large key:\n");
380 {
381 unsigned char buf[512];
382 unsigned char *value;
383 unsigned int vlen, i;
384 for (i = 0; i < 512; i++) buf[i] = 'a';
385
386 zm = zipmapSet(zm,buf,512,(unsigned char*) "long",4,NULL);
387 if (zipmapGet(zm,buf,512,&value,&vlen)) {
388 printf(" <long key> is associated to the %d bytes value: %.*s\n",
389 vlen, vlen, value);
390 }
391 }
392
5234952b 393 printf("\nPerform a direct lookup:\n");
394 {
395 unsigned char *value;
396 unsigned int vlen;
397
398 if (zipmapGet(zm,(unsigned char*) "foo",3,&value,&vlen)) {
399 printf(" foo is associated to the %d bytes value: %.*s\n",
400 vlen, vlen, value);
401 }
402 }
403 printf("\nIterate trought elements:\n");
66ef8da0 404 {
5234952b 405 unsigned char *i = zipmapRewind(zm);
66ef8da0 406 unsigned char *key, *value;
407 unsigned int klen, vlen;
408
409 while((i = zipmapNext(i,&key,&klen,&value,&vlen)) != NULL) {
5234952b 410 printf(" %d:%.*s => %d:%.*s\n", klen, klen, key, vlen, vlen, value);
66ef8da0 411 }
412 }
eb46f4bd 413 return 0;
414}
5234952b 415#endif