zipmap.c 16.5 KB
Newer Older
A
antirez 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
/* String -> String Map data structure optimized for size.
 * This file implements a data structure mapping strings to other strings
 * implementing an O(n) lookup data structure designed to be very memory
 * efficient.
 *
 * The Redis Hash type uses this data structure for hashes composed of a small
 * number of elements, to switch to an hash table once a given number of
 * elements is reached.
 *
 * Given that many times Redis Hashes are used to represent objects composed
 * of few fields, this is a very big win in terms of used memory.
 *
 * --------------------------------------------------------------------------
 *
 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of Redis nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/* Memory layout of a zipmap, for the map "foo" => "bar", "hello" => "world":
 *
45
 * <zmlen><len>"foo"<len><free>"bar"<len>"hello"<len><free>"world"
A
antirez 已提交
46
 *
47 48 49
 * <zmlen> is 1 byte length that holds the current size of the zipmap.
 * When the zipmap length is greater than or equal to 254, this value
 * is not used and the zipmap needs to be traversed to find out the length.
A
antirez 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
 *
 * <len> is the length of the following string (key or value).
 * <len> lengths are encoded in a single value or in a 5 bytes value.
 * If the first byte value (as an unsigned 8 bit value) is between 0 and
 * 252, it's a single-byte length. If it is 253 then a four bytes unsigned
 * integer follows (in the host byte ordering). A value fo 255 is used to
 * signal the end of the hash. The special value 254 is used to mark
 * empty space that can be used to add new key/value pairs.
 *
 * <free> is the number of free unused bytes
 * after the string, resulting from modification of values associated to a
 * key (for instance if "foo" is set to "bar', and later "foo" will be se to
 * "hi", I'll have a free byte to use if the value will enlarge again later,
 * or even in order to add a key/value pair if it fits.
 *
 * <free> is always an unsigned 8 bit number, because if after an
66 67
 * update operation there are more than a few free bytes, the zipmap will be
 * reallocated to make sure it is as small as possible.
A
antirez 已提交
68 69 70
 *
 * The most compact representation of the above two elements hash is actually:
 *
71
 * "\x02\x03foo\x03\x00bar\x05hello\x05\x00world\xff"
A
antirez 已提交
72
 *
73 74
 * Note that because keys and values are prefixed length "objects",
 * the lookup will take O(N) where N is the number of elements
A
antirez 已提交
75 76 77 78 79 80 81 82
 * in the zipmap and *not* the number of bytes needed to represent the zipmap.
 * This lowers the constant times considerably.
 */

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "zmalloc.h"
83
#include "endian.h"
84 85 86

#define ZIPMAP_BIGLEN 254
#define ZIPMAP_END 255
A
antirez 已提交
87 88 89

/* The following defines the max value for the <free> field described in the
 * comments above, that is, the max number of trailing bytes in a value. */
90
#define ZIPMAP_VALUE_MAX_FREE 4
A
antirez 已提交
91

92 93 94 95 96
/* The following macro returns the number of bytes needed to encode the length
 * for the integer value _l, that is, 1 byte for lengths < ZIPMAP_BIGLEN and
 * 5 bytes for all the other lengths. */
#define ZIPMAP_LEN_BYTES(_l) (((_l) < ZIPMAP_BIGLEN) ? 1 : sizeof(unsigned int)+1)

A
antirez 已提交
97 98 99 100
/* Create a new empty zipmap. */
unsigned char *zipmapNew(void) {
    unsigned char *zm = zmalloc(2);

101
    zm[0] = 0; /* Length */
102
    zm[1] = ZIPMAP_END;
A
antirez 已提交
103 104 105
    return zm;
}

106 107 108 109 110 111
/* Decode the encoded length pointed by 'p' */
static unsigned int zipmapDecodeLength(unsigned char *p) {
    unsigned int len = *p;

    if (len < ZIPMAP_BIGLEN) return len;
    memcpy(&len,p+1,sizeof(unsigned int));
112
    memrev32ifbe(&len);
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    return len;
}

/* Encode the length 'l' writing it in 'p'. If p is NULL it just returns
 * the amount of bytes required to encode such a length. */
static unsigned int zipmapEncodeLength(unsigned char *p, unsigned int len) {
    if (p == NULL) {
        return ZIPMAP_LEN_BYTES(len);
    } else {
        if (len < ZIPMAP_BIGLEN) {
            p[0] = len;
            return 1;
        } else {
            p[0] = ZIPMAP_BIGLEN;
            memcpy(p+1,&len,sizeof(len));
128
            memrev32ifbe(p+1);
129 130 131 132 133
            return 1+sizeof(len);
        }
    }
}

A
antirez 已提交
134 135 136 137 138
/* Search for a matching key, returning a pointer to the entry inside the
 * zipmap. Returns NULL if the key is not found.
 *
 * If NULL is returned, and totlen is not NULL, it is set to the entire
 * size of the zimap, so that the calling function will be able to
139
 * reallocate the original zipmap to make room for more entries. */
140 141
static unsigned char *zipmapLookupRaw(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned int *totlen) {
    unsigned char *p = zm+1, *k = NULL;
142
    unsigned int l,llen;
A
antirez 已提交
143

144
    while(*p != ZIPMAP_END) {
145 146 147
        unsigned char free;

        /* Match or skip the key */
148 149
        l = zipmapDecodeLength(p);
        llen = zipmapEncodeLength(NULL,l);
A
antirez 已提交
150
        if (key != NULL && k == NULL && l == klen && !memcmp(p+llen,key,l)) {
151 152 153 154 155 156
            /* Only return when the user doesn't care
             * for the total length of the zipmap. */
            if (totlen != NULL) {
                k = p;
            } else {
                return p;
A
antirez 已提交
157 158
            }
        }
159
        p += llen+l;
160
        /* Skip the value as well */
161 162
        l = zipmapDecodeLength(p);
        p += zipmapEncodeLength(NULL,l);
163 164
        free = p[0];
        p += l+1+free; /* +1 to skip the free byte */
A
antirez 已提交
165 166
    }
    if (totlen != NULL) *totlen = (unsigned int)(p-zm)+1;
167
    return k;
A
antirez 已提交
168 169 170 171 172 173
}

static unsigned long zipmapRequiredLength(unsigned int klen, unsigned int vlen) {
    unsigned int l;

    l = klen+vlen+3;
174 175
    if (klen >= ZIPMAP_BIGLEN) l += 4;
    if (vlen >= ZIPMAP_BIGLEN) l += 4;
A
antirez 已提交
176 177 178
    return l;
}

179
/* Return the total amount used by a key (encoded length + payload) */
A
antirez 已提交
180
static unsigned int zipmapRawKeyLength(unsigned char *p) {
181 182
    unsigned int l = zipmapDecodeLength(p);
    return zipmapEncodeLength(NULL,l) + l;
A
antirez 已提交
183 184
}

185
/* Return the total amount used by a value
A
antirez 已提交
186 187
 * (encoded length + single byte free count + payload) */
static unsigned int zipmapRawValueLength(unsigned char *p) {
188
    unsigned int l = zipmapDecodeLength(p);
A
antirez 已提交
189 190
    unsigned int used;
    
191
    used = zipmapEncodeLength(NULL,l);
A
antirez 已提交
192 193 194 195
    used += p[used] + 1 + l;
    return used;
}

A
antirez 已提交
196 197 198 199 200 201 202 203
/* If 'p' points to a key, this function returns the total amount of
 * bytes used to store this entry (entry = key + associated value + trailing
 * free space if any). */
static unsigned int zipmapRawEntryLength(unsigned char *p) {
    unsigned int l = zipmapRawKeyLength(p);
    return l + zipmapRawValueLength(p+l);
}

204 205 206 207 208 209
static inline unsigned char *zipmapResize(unsigned char *zm, unsigned int len) {
    zm = zrealloc(zm, len);
    zm[len-1] = ZIPMAP_END;
    return zm;
}

210 211 212 213
/* Set key to value, creating the key if it does not already exist.
 * If 'update' is not NULL, *update is set to 1 if the key was
 * already preset, otherwise to 0. */
unsigned char *zipmapSet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char *val, unsigned int vlen, int *update) {
214
    unsigned int zmlen, offset;
215
    unsigned int freelen, reqlen = zipmapRequiredLength(klen,vlen);
A
antirez 已提交
216 217 218 219
    unsigned int empty, vempty;
    unsigned char *p;
   
    freelen = reqlen;
220
    if (update) *update = 0;
221 222 223
    p = zipmapLookupRaw(zm,key,klen,&zmlen);
    if (p == NULL) {
        /* Key not found: enlarge */
224
        zm = zipmapResize(zm, zmlen+reqlen);
225 226
        p = zm+zmlen-1;
        zmlen = zmlen+reqlen;
227 228

        /* Increase zipmap length (this is an insert) */
229
        if (zm[0] < ZIPMAP_BIGLEN) zm[0]++;
A
antirez 已提交
230 231 232
    } else {
        /* Key found. Is there enough space for the new value? */
        /* Compute the total length: */
233
        if (update) *update = 1;
234
        freelen = zipmapRawEntryLength(p);
A
antirez 已提交
235
        if (freelen < reqlen) {
236 237 238 239
            /* Store the offset of this key within the current zipmap, so
             * it can be resized. Then, move the tail backwards so this
             * pair fits at the current position. */
            offset = p-zm;
240
            zm = zipmapResize(zm, zmlen-freelen+reqlen);
241 242 243 244 245 246
            p = zm+offset;

            /* The +1 in the number of bytes to be moved is caused by the
             * end-of-zipmap byte. Note: the *original* zmlen is used. */
            memmove(p+reqlen, p+freelen, zmlen-(offset+freelen+1));
            zmlen = zmlen-freelen+reqlen;
247
            freelen = reqlen;
A
antirez 已提交
248 249 250
        }
    }

251 252 253 254
    /* We now have a suitable block where the key/value entry can
     * be written. If there is too much free space, move the tail
     * of the zipmap a few bytes to the front and shrink the zipmap,
     * as we want zipmaps to be very space efficient. */
A
antirez 已提交
255
    empty = freelen-reqlen;
256
    if (empty >= ZIPMAP_VALUE_MAX_FREE) {
257 258 259 260
        /* First, move the tail <empty> bytes to the front, then resize
         * the zipmap to be <empty> bytes smaller. */
        offset = p-zm;
        memmove(p+reqlen, p+freelen, zmlen-(offset+freelen+1));
261
        zmlen -= empty;
262
        zm = zipmapResize(zm, zmlen);
263
        p = zm+offset;
A
antirez 已提交
264 265 266 267 268 269 270
        vempty = 0;
    } else {
        vempty = empty;
    }

    /* Just write the key + value and we are done. */
    /* Key: */
271
    p += zipmapEncodeLength(p,klen);
A
antirez 已提交
272 273 274
    memcpy(p,key,klen);
    p += klen;
    /* Value: */
275
    p += zipmapEncodeLength(p,vlen);
A
antirez 已提交
276 277 278 279 280
    *p++ = vempty;
    memcpy(p,val,vlen);
    return zm;
}

A
antirez 已提交
281 282 283
/* Remove the specified key. If 'deleted' is not NULL the pointed integer is
 * set to 0 if the key was not found, to 1 if it was found and deleted. */
unsigned char *zipmapDel(unsigned char *zm, unsigned char *key, unsigned int klen, int *deleted) {
284
    unsigned int zmlen, freelen;
285
    unsigned char *p = zipmapLookupRaw(zm,key,klen,&zmlen);
A
antirez 已提交
286
    if (p) {
287
        freelen = zipmapRawEntryLength(p);
288
        memmove(p, p+freelen, zmlen-((p-zm)+freelen+1));
289
        zm = zipmapResize(zm, zmlen-freelen);
290 291

        /* Decrease zipmap length */
292
        if (zm[0] < ZIPMAP_BIGLEN) zm[0]--;
293

A
antirez 已提交
294 295 296 297 298 299 300
        if (deleted) *deleted = 1;
    } else {
        if (deleted) *deleted = 0;
    }
    return zm;
}

J
Jason Davies 已提交
301
/* Call before iterating through elements via zipmapNext() */
302 303 304 305
unsigned char *zipmapRewind(unsigned char *zm) {
    return zm+1;
}

A
antirez 已提交
306 307 308 309 310
/* This function is used to iterate through all the zipmap elements.
 * In the first call the first argument is the pointer to the zipmap + 1.
 * In the next calls what zipmapNext returns is used as first argument.
 * Example:
 *
311
 * unsigned char *i = zipmapRewind(my_zipmap);
A
antirez 已提交
312 313 314 315 316
 * while((i = zipmapNext(i,&key,&klen,&value,&vlen)) != NULL) {
 *     printf("%d bytes key at $p\n", klen, key);
 *     printf("%d bytes value at $p\n", vlen, value);
 * }
 */
317
unsigned char *zipmapNext(unsigned char *zm, unsigned char **key, unsigned int *klen, unsigned char **value, unsigned int *vlen) {
318
    if (zm[0] == ZIPMAP_END) return NULL;
A
antirez 已提交
319 320
    if (key) {
        *key = zm;
321 322
        *klen = zipmapDecodeLength(zm);
        *key += ZIPMAP_LEN_BYTES(*klen);
A
antirez 已提交
323 324 325 326
    }
    zm += zipmapRawKeyLength(zm);
    if (value) {
        *value = zm+1;
327 328
        *vlen = zipmapDecodeLength(zm);
        *value += ZIPMAP_LEN_BYTES(*vlen);
A
antirez 已提交
329 330 331 332 333
    }
    zm += zipmapRawValueLength(zm);
    return zm;
}

334 335 336 337 338
/* Search a key and retrieve the pointer and len of the associated value.
 * If the key is found the function returns 1, otherwise 0. */
int zipmapGet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char **value, unsigned int *vlen) {
    unsigned char *p;

339
    if ((p = zipmapLookupRaw(zm,key,klen,NULL)) == NULL) return 0;
340
    p += zipmapRawKeyLength(p);
341 342
    *vlen = zipmapDecodeLength(p);
    *value = p + ZIPMAP_LEN_BYTES(*vlen) + 1;
343 344 345 346 347
    return 1;
}

/* Return 1 if the key exists, otherwise 0 is returned. */
int zipmapExists(unsigned char *zm, unsigned char *key, unsigned int klen) {
348
    return zipmapLookupRaw(zm,key,klen,NULL) != NULL;
349 350
}

A
antirez 已提交
351 352 353
/* Return the number of entries inside a zipmap */
unsigned int zipmapLen(unsigned char *zm) {
    unsigned int len = 0;
354
    if (zm[0] < ZIPMAP_BIGLEN) {
355 356 357 358
        len = zm[0];
    } else {
        unsigned char *p = zipmapRewind(zm);
        while((p = zipmapNext(p,NULL,NULL,NULL,NULL)) != NULL) len++;
A
antirez 已提交
359

360
        /* Re-store length if small enough */
361
        if (len < ZIPMAP_BIGLEN) zm[0] = len;
362
    }
A
antirez 已提交
363 364 365
    return len;
}

366 367 368 369
/* Return the raw size in bytes of a zipmap, so that we can serialize
 * the zipmap on disk (or everywhere is needed) just writing the returned
 * amount of bytes of the C array starting at the zipmap pointer. */
size_t zipmapBlobLen(unsigned char *zm) {
A
antirez 已提交
370 371 372
    unsigned int totlen;
    zipmapLookupRaw(zm,NULL,0,&totlen);
    return totlen;
373 374
}

A
antirez 已提交
375
#ifdef ZIPMAP_TEST_MAIN
A
antirez 已提交
376 377 378 379 380
void zipmapRepr(unsigned char *p) {
    unsigned int l;

    printf("{status %u}",*p++);
    while(1) {
381
        if (p[0] == ZIPMAP_END) {
A
antirez 已提交
382 383 384 385 386
            printf("{end}");
            break;
        } else {
            unsigned char e;

387
            l = zipmapDecodeLength(p);
A
antirez 已提交
388
            printf("{key %u}",l);
389
            p += zipmapEncodeLength(NULL,l);
390
            if (l != 0 && fwrite(p,l,1,stdout) == 0) perror("fwrite");
A
antirez 已提交
391 392
            p += l;

393
            l = zipmapDecodeLength(p);
A
antirez 已提交
394
            printf("{value %u}",l);
395
            p += zipmapEncodeLength(NULL,l);
A
antirez 已提交
396
            e = *p++;
397
            if (l != 0 && fwrite(p,l,1,stdout) == 0) perror("fwrite");
398
            p += l+e;
A
antirez 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412
            if (e) {
                printf("[");
                while(e--) printf(".");
                printf("]");
            }
        }
    }
    printf("\n");
}

int main(void) {
    unsigned char *zm;

    zm = zipmapNew();
413 414 415 416 417 418

    zm = zipmapSet(zm,(unsigned char*) "name",4, (unsigned char*) "foo",3,NULL);
    zm = zipmapSet(zm,(unsigned char*) "surname",7, (unsigned char*) "foo",3,NULL);
    zm = zipmapSet(zm,(unsigned char*) "age",3, (unsigned char*) "foo",3,NULL);
    zipmapRepr(zm);

419 420 421
    zm = zipmapSet(zm,(unsigned char*) "hello",5, (unsigned char*) "world!",6,NULL);
    zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "bar",3,NULL);
    zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "!",1,NULL);
A
antirez 已提交
422
    zipmapRepr(zm);
423
    zm = zipmapSet(zm,(unsigned char*) "foo",3, (unsigned char*) "12345",5,NULL);
A
antirez 已提交
424
    zipmapRepr(zm);
425
    zm = zipmapSet(zm,(unsigned char*) "new",3, (unsigned char*) "xx",2,NULL);
426
    zm = zipmapSet(zm,(unsigned char*) "noval",5, (unsigned char*) "",0,NULL);
A
antirez 已提交
427
    zipmapRepr(zm);
A
antirez 已提交
428 429
    zm = zipmapDel(zm,(unsigned char*) "new",3,NULL);
    zipmapRepr(zm);
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444

    printf("\nLook up large key:\n");
    {
        unsigned char buf[512];
        unsigned char *value;
        unsigned int vlen, i;
        for (i = 0; i < 512; i++) buf[i] = 'a';

        zm = zipmapSet(zm,buf,512,(unsigned char*) "long",4,NULL);
        if (zipmapGet(zm,buf,512,&value,&vlen)) {
            printf("  <long key> is associated to the %d bytes value: %.*s\n",
                vlen, vlen, value);
        }
    }

445 446 447 448 449 450 451 452 453 454
    printf("\nPerform a direct lookup:\n");
    {
        unsigned char *value;
        unsigned int vlen;

        if (zipmapGet(zm,(unsigned char*) "foo",3,&value,&vlen)) {
            printf("  foo is associated to the %d bytes value: %.*s\n",
                vlen, vlen, value);
        }
    }
J
Jason Davies 已提交
455
    printf("\nIterate through elements:\n");
A
antirez 已提交
456
    {
457
        unsigned char *i = zipmapRewind(zm);
A
antirez 已提交
458 459 460 461
        unsigned char *key, *value;
        unsigned int klen, vlen;

        while((i = zipmapNext(i,&key,&klen,&value,&vlen)) != NULL) {
462
            printf("  %d:%.*s => %d:%.*s\n", klen, klen, key, vlen, vlen, value);
A
antirez 已提交
463 464
        }
    }
A
antirez 已提交
465 466
    return 0;
}
467
#endif