]> git.saurik.com Git - redis.git/blame_incremental - src/ziplist.c
free memory if the maxmemory parameter is reduced via CONFIG SET
[redis.git] / src / ziplist.c
... / ...
CommitLineData
1/* The ziplist is a specially encoded dually linked list that is designed
2 * to be very memory efficient. It stores both strings and integer values,
3 * where integers are encoded as actual integers instead of a series of
4 * characters. It allows push and pop operations on either side of the list
5 * in O(1) time. However, because every operation requires a reallocation of
6 * the memory used by the ziplist, the actual complexity is related to the
7 * amount of memory used by the ziplist.
8 *
9 * ----------------------------------------------------------------------------
10 *
11 * ZIPLIST OVERALL LAYOUT:
12 * The general layout of the ziplist is as follows:
13 * <zlbytes><zltail><zllen><entry><entry><zlend>
14 *
15 * <zlbytes> is an unsigned integer to hold the number of bytes that the
16 * ziplist occupies. This value needs to be stored to be able to resize the
17 * entire structure without the need to traverse it first.
18 *
19 * <zltail> is the offset to the last entry in the list. This allows a pop
20 * operation on the far side of the list without the need for full traversal.
21 *
22 * <zllen> is the number of entries.When this value is larger than 2**16-2,
23 * we need to traverse the entire list to know how many items it holds.
24 *
25 * <zlend> is a single byte special value, equal to 255, which indicates the
26 * end of the list.
27 *
28 * ZIPLIST ENTRIES:
29 * Every entry in the ziplist is prefixed by a header that contains two pieces
30 * of information. First, the length of the previous entry is stored to be
31 * able to traverse the list from back to front. Second, the encoding with an
32 * optional string length of the entry itself is stored.
33 *
34 * The length of the previous entry is encoded in the following way:
35 * If this length is smaller than 254 bytes, it will only consume a single
36 * byte that takes the length as value. When the length is greater than or
37 * equal to 254, it will consume 5 bytes. The first byte is set to 254 to
38 * indicate a larger value is following. The remaining 4 bytes take the
39 * length of the previous entry as value.
40 *
41 * The other header field of the entry itself depends on the contents of the
42 * entry. When the entry is a string, the first 2 bits of this header will hold
43 * the type of encoding used to store the length of the string, followed by the
44 * actual length of the string. When the entry is an integer the first 2 bits
45 * are both set to 1. The following 2 bits are used to specify what kind of
46 * integer will be stored after this header. An overview of the different
47 * types and encodings is as follows:
48 *
49 * |00pppppp| - 1 byte
50 * String value with length less than or equal to 63 bytes (6 bits).
51 * |01pppppp|qqqqqqqq| - 2 bytes
52 * String value with length less than or equal to 16383 bytes (14 bits).
53 * |10______|qqqqqqqq|rrrrrrrr|ssssssss|tttttttt| - 5 bytes
54 * String value with length greater than or equal to 16384 bytes.
55 * |1100____| - 1 byte
56 * Integer encoded as int16_t (2 bytes).
57 * |1101____| - 1 byte
58 * Integer encoded as int32_t (4 bytes).
59 * |1110____| - 1 byte
60 * Integer encoded as int64_t (8 bytes).
61 */
62
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66#include <stdint.h>
67#include <assert.h>
68#include <limits.h>
69#include "zmalloc.h"
70#include "ziplist.h"
71
72int ll2string(char *s, size_t len, long long value);
73
74#define ZIP_END 255
75#define ZIP_BIGLEN 254
76
77/* Different encoding/length possibilities */
78#define ZIP_STR_06B (0 << 6)
79#define ZIP_STR_14B (1 << 6)
80#define ZIP_STR_32B (2 << 6)
81#define ZIP_INT_16B (0xc0 | 0<<4)
82#define ZIP_INT_32B (0xc0 | 1<<4)
83#define ZIP_INT_64B (0xc0 | 2<<4)
84
85/* Macro's to determine type */
86#define ZIP_IS_STR(enc) (((enc) & 0xc0) < 0xc0)
87#define ZIP_IS_INT(enc) (!ZIP_IS_STR(enc) && ((enc) & 0x30) < 0x30)
88
89/* Utility macros */
90#define ZIPLIST_BYTES(zl) (*((uint32_t*)(zl)))
91#define ZIPLIST_TAIL_OFFSET(zl) (*((uint32_t*)((zl)+sizeof(uint32_t))))
92#define ZIPLIST_LENGTH(zl) (*((uint16_t*)((zl)+sizeof(uint32_t)*2)))
93#define ZIPLIST_HEADER_SIZE (sizeof(uint32_t)*2+sizeof(uint16_t))
94#define ZIPLIST_ENTRY_HEAD(zl) ((zl)+ZIPLIST_HEADER_SIZE)
95#define ZIPLIST_ENTRY_TAIL(zl) ((zl)+ZIPLIST_TAIL_OFFSET(zl))
96#define ZIPLIST_ENTRY_END(zl) ((zl)+ZIPLIST_BYTES(zl)-1)
97
98/* We know a positive increment can only be 1 because entries can only be
99 * pushed one at a time. */
100#define ZIPLIST_INCR_LENGTH(zl,incr) { \
101 if (ZIPLIST_LENGTH(zl) < UINT16_MAX) ZIPLIST_LENGTH(zl)+=incr; }
102
103typedef struct zlentry {
104 unsigned int prevrawlensize, prevrawlen;
105 unsigned int lensize, len;
106 unsigned int headersize;
107 unsigned char encoding;
108 unsigned char *p;
109} zlentry;
110
111/* Return the encoding pointer to by 'p'. */
112static unsigned int zipEntryEncoding(unsigned char *p) {
113 /* String encoding: 2 MSBs */
114 unsigned char b = p[0] & 0xc0;
115 if (b < 0xc0) {
116 return b;
117 } else {
118 /* Integer encoding: 4 MSBs */
119 return p[0] & 0xf0;
120 }
121 assert(NULL);
122}
123
124/* Return bytes needed to store integer encoded by 'encoding' */
125static unsigned int zipIntSize(unsigned char encoding) {
126 switch(encoding) {
127 case ZIP_INT_16B: return sizeof(int16_t);
128 case ZIP_INT_32B: return sizeof(int32_t);
129 case ZIP_INT_64B: return sizeof(int64_t);
130 }
131 assert(NULL);
132}
133
134/* Decode the encoded length pointed by 'p'. If a pointer to 'lensize' is
135 * provided, it is set to the number of bytes required to encode the length. */
136static unsigned int zipDecodeLength(unsigned char *p, unsigned int *lensize) {
137 unsigned char encoding = zipEntryEncoding(p);
138 unsigned int len;
139
140 if (ZIP_IS_STR(encoding)) {
141 switch(encoding) {
142 case ZIP_STR_06B:
143 len = p[0] & 0x3f;
144 if (lensize) *lensize = 1;
145 break;
146 case ZIP_STR_14B:
147 len = ((p[0] & 0x3f) << 8) | p[1];
148 if (lensize) *lensize = 2;
149 break;
150 case ZIP_STR_32B:
151 len = (p[1] << 24) | (p[2] << 16) | (p[3] << 8) | p[4];
152 if (lensize) *lensize = 5;
153 break;
154 default:
155 assert(NULL);
156 }
157 } else {
158 len = zipIntSize(encoding);
159 if (lensize) *lensize = 1;
160 }
161 return len;
162}
163
164/* Encode the length 'l' writing it in 'p'. If p is NULL it just returns
165 * the amount of bytes required to encode such a length. */
166static unsigned int zipEncodeLength(unsigned char *p, unsigned char encoding, unsigned int rawlen) {
167 unsigned char len = 1, buf[5];
168
169 if (ZIP_IS_STR(encoding)) {
170 /* Although encoding is given it may not be set for strings,
171 * so we determine it here using the raw length. */
172 if (rawlen <= 0x3f) {
173 if (!p) return len;
174 buf[0] = ZIP_STR_06B | rawlen;
175 } else if (rawlen <= 0x3fff) {
176 len += 1;
177 if (!p) return len;
178 buf[0] = ZIP_STR_14B | ((rawlen >> 8) & 0x3f);
179 buf[1] = rawlen & 0xff;
180 } else {
181 len += 4;
182 if (!p) return len;
183 buf[0] = ZIP_STR_32B;
184 buf[1] = (rawlen >> 24) & 0xff;
185 buf[2] = (rawlen >> 16) & 0xff;
186 buf[3] = (rawlen >> 8) & 0xff;
187 buf[4] = rawlen & 0xff;
188 }
189 } else {
190 /* Implies integer encoding, so length is always 1. */
191 if (!p) return len;
192 buf[0] = encoding;
193 }
194
195 /* Store this length at p */
196 memcpy(p,buf,len);
197 return len;
198}
199
200/* Decode the length of the previous element stored at "p". */
201static unsigned int zipPrevDecodeLength(unsigned char *p, unsigned int *lensize) {
202 unsigned int len = *p;
203 if (len < ZIP_BIGLEN) {
204 if (lensize) *lensize = 1;
205 } else {
206 if (lensize) *lensize = 1+sizeof(len);
207 memcpy(&len,p+1,sizeof(len));
208 }
209 return len;
210}
211
212/* Encode the length of the previous entry and write it to "p". Return the
213 * number of bytes needed to encode this length if "p" is NULL. */
214static unsigned int zipPrevEncodeLength(unsigned char *p, unsigned int len) {
215 if (p == NULL) {
216 return (len < ZIP_BIGLEN) ? 1 : sizeof(len)+1;
217 } else {
218 if (len < ZIP_BIGLEN) {
219 p[0] = len;
220 return 1;
221 } else {
222 p[0] = ZIP_BIGLEN;
223 memcpy(p+1,&len,sizeof(len));
224 return 1+sizeof(len);
225 }
226 }
227}
228
229/* Encode the length of the previous entry and write it to "p". This only
230 * uses the larger encoding (required in __ziplistCascadeUpdate). */
231static void zipPrevEncodeLengthForceLarge(unsigned char *p, unsigned int len) {
232 if (p == NULL) return;
233 p[0] = ZIP_BIGLEN;
234 memcpy(p+1,&len,sizeof(len));
235}
236
237/* Return the difference in number of bytes needed to store the new length
238 * "len" on the entry pointed to by "p". */
239static int zipPrevLenByteDiff(unsigned char *p, unsigned int len) {
240 unsigned int prevlensize;
241 zipPrevDecodeLength(p,&prevlensize);
242 return zipPrevEncodeLength(NULL,len)-prevlensize;
243}
244
245/* Check if string pointed to by 'entry' can be encoded as an integer.
246 * Stores the integer value in 'v' and its encoding in 'encoding'. */
247static int zipTryEncoding(unsigned char *entry, unsigned int entrylen, long long *v, unsigned char *encoding) {
248 long long value;
249 char *eptr;
250 char buf[32];
251
252 if (entrylen >= 32 || entrylen == 0) return 0;
253 if (entry[0] == '-' || (entry[0] >= '0' && entry[0] <= '9')) {
254 int slen;
255
256 /* Perform a back-and-forth conversion to make sure that
257 * the string turned into an integer is not losing any info. */
258 memcpy(buf,entry,entrylen);
259 buf[entrylen] = '\0';
260 value = strtoll(buf,&eptr,10);
261 if (eptr[0] != '\0') return 0;
262 slen = ll2string(buf,32,value);
263 if (entrylen != (unsigned)slen || memcmp(buf,entry,slen)) return 0;
264
265 /* Great, the string can be encoded. Check what's the smallest
266 * of our encoding types that can hold this value. */
267 if (value >= INT16_MIN && value <= INT16_MAX) {
268 *encoding = ZIP_INT_16B;
269 } else if (value >= INT32_MIN && value <= INT32_MAX) {
270 *encoding = ZIP_INT_32B;
271 } else {
272 *encoding = ZIP_INT_64B;
273 }
274 *v = value;
275 return 1;
276 }
277 return 0;
278}
279
280/* Store integer 'value' at 'p', encoded as 'encoding' */
281static void zipSaveInteger(unsigned char *p, int64_t value, unsigned char encoding) {
282 int16_t i16;
283 int32_t i32;
284 int64_t i64;
285 if (encoding == ZIP_INT_16B) {
286 i16 = value;
287 memcpy(p,&i16,sizeof(i16));
288 } else if (encoding == ZIP_INT_32B) {
289 i32 = value;
290 memcpy(p,&i32,sizeof(i32));
291 } else if (encoding == ZIP_INT_64B) {
292 i64 = value;
293 memcpy(p,&i64,sizeof(i64));
294 } else {
295 assert(NULL);
296 }
297}
298
299/* Read integer encoded as 'encoding' from 'p' */
300static int64_t zipLoadInteger(unsigned char *p, unsigned char encoding) {
301 int16_t i16;
302 int32_t i32;
303 int64_t i64, ret;
304 if (encoding == ZIP_INT_16B) {
305 memcpy(&i16,p,sizeof(i16));
306 ret = i16;
307 } else if (encoding == ZIP_INT_32B) {
308 memcpy(&i32,p,sizeof(i32));
309 ret = i32;
310 } else if (encoding == ZIP_INT_64B) {
311 memcpy(&i64,p,sizeof(i64));
312 ret = i64;
313 } else {
314 assert(NULL);
315 }
316 return ret;
317}
318
319/* Return a struct with all information about an entry. */
320static zlentry zipEntry(unsigned char *p) {
321 zlentry e;
322 e.prevrawlen = zipPrevDecodeLength(p,&e.prevrawlensize);
323 e.len = zipDecodeLength(p+e.prevrawlensize,&e.lensize);
324 e.headersize = e.prevrawlensize+e.lensize;
325 e.encoding = zipEntryEncoding(p+e.prevrawlensize);
326 e.p = p;
327 return e;
328}
329
330/* Return the total number of bytes used by the entry at "p". */
331static unsigned int zipRawEntryLength(unsigned char *p) {
332 zlentry e = zipEntry(p);
333 return e.headersize + e.len;
334}
335
336/* Create a new empty ziplist. */
337unsigned char *ziplistNew(void) {
338 unsigned int bytes = ZIPLIST_HEADER_SIZE+1;
339 unsigned char *zl = zmalloc(bytes);
340 ZIPLIST_BYTES(zl) = bytes;
341 ZIPLIST_TAIL_OFFSET(zl) = ZIPLIST_HEADER_SIZE;
342 ZIPLIST_LENGTH(zl) = 0;
343 zl[bytes-1] = ZIP_END;
344 return zl;
345}
346
347/* Resize the ziplist. */
348static unsigned char *ziplistResize(unsigned char *zl, unsigned int len) {
349 zl = zrealloc(zl,len);
350 ZIPLIST_BYTES(zl) = len;
351 zl[len-1] = ZIP_END;
352 return zl;
353}
354
355/* When an entry is inserted, we need to set the prevlen field of the next
356 * entry to equal the length of the inserted entry. It can occur that this
357 * length cannot be encoded in 1 byte and the next entry needs to be grow
358 * a bit larger to hold the 5-byte encoded prevlen. This can be done for free,
359 * because this only happens when an entry is already being inserted (which
360 * causes a realloc and memmove). However, encoding the prevlen may require
361 * that this entry is grown as well. This effect may cascade throughout
362 * the ziplist when there are consecutive entries with a size close to
363 * ZIP_BIGLEN, so we need to check that the prevlen can be encoded in every
364 * consecutive entry.
365 *
366 * Note that this effect can also happen in reverse, where the bytes required
367 * to encode the prevlen field can shrink. This effect is deliberately ignored,
368 * because it can cause a "flapping" effect where a chain prevlen fields is
369 * first grown and then shrunk again after consecutive inserts. Rather, the
370 * field is allowed to stay larger than necessary, because a large prevlen
371 * field implies the ziplist is holding large entries anyway.
372 *
373 * The pointer "p" points to the first entry that does NOT need to be
374 * updated, i.e. consecutive fields MAY need an update. */
375static unsigned char *__ziplistCascadeUpdate(unsigned char *zl, unsigned char *p) {
376 unsigned int curlen = ZIPLIST_BYTES(zl), rawlen, rawlensize;
377 unsigned int offset, noffset, extra;
378 unsigned char *np;
379 zlentry cur, next;
380
381 while (p[0] != ZIP_END) {
382 cur = zipEntry(p);
383 rawlen = cur.headersize + cur.len;
384 rawlensize = zipPrevEncodeLength(NULL,rawlen);
385
386 /* Abort if there is no next entry. */
387 if (p[rawlen] == ZIP_END) break;
388 next = zipEntry(p+rawlen);
389
390 /* Abort when "prevlen" has not changed. */
391 if (next.prevrawlen == rawlen) break;
392
393 if (next.prevrawlensize < rawlensize) {
394 /* The "prevlen" field of "next" needs more bytes to hold
395 * the raw length of "cur". */
396 offset = p-zl;
397 extra = rawlensize-next.prevrawlensize;
398 zl = ziplistResize(zl,curlen+extra);
399 ZIPLIST_TAIL_OFFSET(zl) += extra;
400 p = zl+offset;
401
402 /* Move the tail to the back. */
403 np = p+rawlen;
404 noffset = np-zl;
405 memmove(np+rawlensize,
406 np+next.prevrawlensize,
407 curlen-noffset-next.prevrawlensize-1);
408 zipPrevEncodeLength(np,rawlen);
409
410 /* Advance the cursor */
411 p += rawlen;
412 } else {
413 if (next.prevrawlensize > rawlensize) {
414 /* This would result in shrinking, which we want to avoid.
415 * So, set "rawlen" in the available bytes. */
416 zipPrevEncodeLengthForceLarge(p+rawlen,rawlen);
417 } else {
418 zipPrevEncodeLength(p+rawlen,rawlen);
419 }
420
421 /* Stop here, as the raw length of "next" has not changed. */
422 break;
423 }
424 }
425 return zl;
426}
427
428/* Delete "num" entries, starting at "p". Returns pointer to the ziplist. */
429static unsigned char *__ziplistDelete(unsigned char *zl, unsigned char *p, unsigned int num) {
430 unsigned int i, totlen, deleted = 0;
431 int offset, nextdiff = 0;
432 zlentry first, tail;
433
434 first = zipEntry(p);
435 for (i = 0; p[0] != ZIP_END && i < num; i++) {
436 p += zipRawEntryLength(p);
437 deleted++;
438 }
439
440 totlen = p-first.p;
441 if (totlen > 0) {
442 if (p[0] != ZIP_END) {
443 /* Tricky: storing the prevlen in this entry might reduce or
444 * increase the number of bytes needed, compared to the current
445 * prevlen. Note that we can always store this length because
446 * it was previously stored by an entry that is being deleted. */
447 nextdiff = zipPrevLenByteDiff(p,first.prevrawlen);
448 zipPrevEncodeLength(p-nextdiff,first.prevrawlen);
449
450 /* Update offset for tail */
451 ZIPLIST_TAIL_OFFSET(zl) -= totlen;
452
453 /* When the tail contains more than one entry, we need to take
454 * "nextdiff" in account as well. Otherwise, a change in the
455 * size of prevlen doesn't have an effect on the *tail* offset. */
456 tail = zipEntry(p);
457 if (p[tail.headersize+tail.len] != ZIP_END)
458 ZIPLIST_TAIL_OFFSET(zl) += nextdiff;
459
460 /* Move tail to the front of the ziplist */
461 memmove(first.p,p-nextdiff,ZIPLIST_BYTES(zl)-(p-zl)-1+nextdiff);
462 } else {
463 /* The entire tail was deleted. No need to move memory. */
464 ZIPLIST_TAIL_OFFSET(zl) = (first.p-zl)-first.prevrawlen;
465 }
466
467 /* Resize and update length */
468 offset = first.p-zl;
469 zl = ziplistResize(zl, ZIPLIST_BYTES(zl)-totlen+nextdiff);
470 ZIPLIST_INCR_LENGTH(zl,-deleted);
471 p = zl+offset;
472
473 /* When nextdiff != 0, the raw length of the next entry has changed, so
474 * we need to cascade the update throughout the ziplist */
475 if (nextdiff != 0)
476 zl = __ziplistCascadeUpdate(zl,p);
477 }
478 return zl;
479}
480
481/* Insert item at "p". */
482static unsigned char *__ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen) {
483 unsigned int curlen = ZIPLIST_BYTES(zl), reqlen, prevlen = 0;
484 unsigned int offset, nextdiff = 0;
485 unsigned char encoding = 0;
486 long long value;
487 zlentry entry, tail;
488
489 /* Find out prevlen for the entry that is inserted. */
490 if (p[0] != ZIP_END) {
491 entry = zipEntry(p);
492 prevlen = entry.prevrawlen;
493 } else {
494 unsigned char *ptail = ZIPLIST_ENTRY_TAIL(zl);
495 if (ptail[0] != ZIP_END) {
496 prevlen = zipRawEntryLength(ptail);
497 }
498 }
499
500 /* See if the entry can be encoded */
501 if (zipTryEncoding(s,slen,&value,&encoding)) {
502 /* 'encoding' is set to the appropriate integer encoding */
503 reqlen = zipIntSize(encoding);
504 } else {
505 /* 'encoding' is untouched, however zipEncodeLength will use the
506 * string length to figure out how to encode it. */
507 reqlen = slen;
508 }
509 /* We need space for both the length of the previous entry and
510 * the length of the payload. */
511 reqlen += zipPrevEncodeLength(NULL,prevlen);
512 reqlen += zipEncodeLength(NULL,encoding,slen);
513
514 /* When the insert position is not equal to the tail, we need to
515 * make sure that the next entry can hold this entry's length in
516 * its prevlen field. */
517 nextdiff = (p[0] != ZIP_END) ? zipPrevLenByteDiff(p,reqlen) : 0;
518
519 /* Store offset because a realloc may change the address of zl. */
520 offset = p-zl;
521 zl = ziplistResize(zl,curlen+reqlen+nextdiff);
522 p = zl+offset;
523
524 /* Apply memory move when necessary and update tail offset. */
525 if (p[0] != ZIP_END) {
526 /* Subtract one because of the ZIP_END bytes */
527 memmove(p+reqlen,p-nextdiff,curlen-offset-1+nextdiff);
528
529 /* Encode this entry's raw length in the next entry. */
530 zipPrevEncodeLength(p+reqlen,reqlen);
531
532 /* Update offset for tail */
533 ZIPLIST_TAIL_OFFSET(zl) += reqlen;
534
535 /* When the tail contains more than one entry, we need to take
536 * "nextdiff" in account as well. Otherwise, a change in the
537 * size of prevlen doesn't have an effect on the *tail* offset. */
538 tail = zipEntry(p+reqlen);
539 if (p[reqlen+tail.headersize+tail.len] != ZIP_END)
540 ZIPLIST_TAIL_OFFSET(zl) += nextdiff;
541 } else {
542 /* This element will be the new tail. */
543 ZIPLIST_TAIL_OFFSET(zl) = p-zl;
544 }
545
546 /* When nextdiff != 0, the raw length of the next entry has changed, so
547 * we need to cascade the update throughout the ziplist */
548 if (nextdiff != 0) {
549 offset = p-zl;
550 zl = __ziplistCascadeUpdate(zl,p+reqlen);
551 p = zl+offset;
552 }
553
554 /* Write the entry */
555 p += zipPrevEncodeLength(p,prevlen);
556 p += zipEncodeLength(p,encoding,slen);
557 if (ZIP_IS_STR(encoding)) {
558 memcpy(p,s,slen);
559 } else {
560 zipSaveInteger(p,value,encoding);
561 }
562 ZIPLIST_INCR_LENGTH(zl,1);
563 return zl;
564}
565
566unsigned char *ziplistPush(unsigned char *zl, unsigned char *s, unsigned int slen, int where) {
567 unsigned char *p;
568 p = (where == ZIPLIST_HEAD) ? ZIPLIST_ENTRY_HEAD(zl) : ZIPLIST_ENTRY_END(zl);
569 return __ziplistInsert(zl,p,s,slen);
570}
571
572/* Returns an offset to use for iterating with ziplistNext. When the given
573 * index is negative, the list is traversed back to front. When the list
574 * doesn't contain an element at the provided index, NULL is returned. */
575unsigned char *ziplistIndex(unsigned char *zl, int index) {
576 unsigned char *p;
577 zlentry entry;
578 if (index < 0) {
579 index = (-index)-1;
580 p = ZIPLIST_ENTRY_TAIL(zl);
581 if (p[0] != ZIP_END) {
582 entry = zipEntry(p);
583 while (entry.prevrawlen > 0 && index--) {
584 p -= entry.prevrawlen;
585 entry = zipEntry(p);
586 }
587 }
588 } else {
589 p = ZIPLIST_ENTRY_HEAD(zl);
590 while (p[0] != ZIP_END && index--) {
591 p += zipRawEntryLength(p);
592 }
593 }
594 return (p[0] == ZIP_END || index > 0) ? NULL : p;
595}
596
597/* Return pointer to next entry in ziplist. */
598unsigned char *ziplistNext(unsigned char *zl, unsigned char *p) {
599 ((void) zl);
600
601 /* "p" could be equal to ZIP_END, caused by ziplistDelete,
602 * and we should return NULL. Otherwise, we should return NULL
603 * when the *next* element is ZIP_END (there is no next entry). */
604 if (p[0] == ZIP_END) {
605 return NULL;
606 } else {
607 p = p+zipRawEntryLength(p);
608 return (p[0] == ZIP_END) ? NULL : p;
609 }
610}
611
612/* Return pointer to previous entry in ziplist. */
613unsigned char *ziplistPrev(unsigned char *zl, unsigned char *p) {
614 zlentry entry;
615
616 /* Iterating backwards from ZIP_END should return the tail. When "p" is
617 * equal to the first element of the list, we're already at the head,
618 * and should return NULL. */
619 if (p[0] == ZIP_END) {
620 p = ZIPLIST_ENTRY_TAIL(zl);
621 return (p[0] == ZIP_END) ? NULL : p;
622 } else if (p == ZIPLIST_ENTRY_HEAD(zl)) {
623 return NULL;
624 } else {
625 entry = zipEntry(p);
626 assert(entry.prevrawlen > 0);
627 return p-entry.prevrawlen;
628 }
629}
630
631/* Get entry pointer to by 'p' and store in either 'e' or 'v' depending
632 * on the encoding of the entry. 'e' is always set to NULL to be able
633 * to find out whether the string pointer or the integer value was set.
634 * Return 0 if 'p' points to the end of the zipmap, 1 otherwise. */
635unsigned int ziplistGet(unsigned char *p, unsigned char **sstr, unsigned int *slen, long long *sval) {
636 zlentry entry;
637 if (p == NULL || p[0] == ZIP_END) return 0;
638 if (sstr) *sstr = NULL;
639
640 entry = zipEntry(p);
641 if (ZIP_IS_STR(entry.encoding)) {
642 if (sstr) {
643 *slen = entry.len;
644 *sstr = p+entry.headersize;
645 }
646 } else {
647 if (sval) {
648 *sval = zipLoadInteger(p+entry.headersize,entry.encoding);
649 }
650 }
651 return 1;
652}
653
654/* Insert an entry at "p". */
655unsigned char *ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen) {
656 return __ziplistInsert(zl,p,s,slen);
657}
658
659/* Delete a single entry from the ziplist, pointed to by *p.
660 * Also update *p in place, to be able to iterate over the
661 * ziplist, while deleting entries. */
662unsigned char *ziplistDelete(unsigned char *zl, unsigned char **p) {
663 unsigned int offset = *p-zl;
664 zl = __ziplistDelete(zl,*p,1);
665
666 /* Store pointer to current element in p, because ziplistDelete will
667 * do a realloc which might result in a different "zl"-pointer.
668 * When the delete direction is back to front, we might delete the last
669 * entry and end up with "p" pointing to ZIP_END, so check this. */
670 *p = zl+offset;
671 return zl;
672}
673
674/* Delete a range of entries from the ziplist. */
675unsigned char *ziplistDeleteRange(unsigned char *zl, unsigned int index, unsigned int num) {
676 unsigned char *p = ziplistIndex(zl,index);
677 return (p == NULL) ? zl : __ziplistDelete(zl,p,num);
678}
679
680/* Compare entry pointer to by 'p' with 'entry'. Return 1 if equal. */
681unsigned int ziplistCompare(unsigned char *p, unsigned char *sstr, unsigned int slen) {
682 zlentry entry;
683 unsigned char sencoding;
684 long long zval, sval;
685 if (p[0] == ZIP_END) return 0;
686
687 entry = zipEntry(p);
688 if (ZIP_IS_STR(entry.encoding)) {
689 /* Raw compare */
690 if (entry.len == slen) {
691 return memcmp(p+entry.headersize,sstr,slen) == 0;
692 } else {
693 return 0;
694 }
695 } else {
696 /* Try to compare encoded values */
697 if (zipTryEncoding(sstr,slen,&sval,&sencoding)) {
698 if (entry.encoding == sencoding) {
699 zval = zipLoadInteger(p+entry.headersize,entry.encoding);
700 return zval == sval;
701 }
702 }
703 }
704 return 0;
705}
706
707/* Return length of ziplist. */
708unsigned int ziplistLen(unsigned char *zl) {
709 unsigned int len = 0;
710 if (ZIPLIST_LENGTH(zl) < UINT16_MAX) {
711 len = ZIPLIST_LENGTH(zl);
712 } else {
713 unsigned char *p = zl+ZIPLIST_HEADER_SIZE;
714 while (*p != ZIP_END) {
715 p += zipRawEntryLength(p);
716 len++;
717 }
718
719 /* Re-store length if small enough */
720 if (len < UINT16_MAX) ZIPLIST_LENGTH(zl) = len;
721 }
722 return len;
723}
724
725/* Return size in bytes of ziplist. */
726unsigned int ziplistSize(unsigned char *zl) {
727 return ZIPLIST_BYTES(zl);
728}
729
730void ziplistRepr(unsigned char *zl) {
731 unsigned char *p;
732 int index = 0;
733 zlentry entry;
734
735 printf(
736 "{total bytes %d} "
737 "{length %u}\n"
738 "{tail offset %u}\n",
739 ZIPLIST_BYTES(zl),
740 ZIPLIST_LENGTH(zl),
741 ZIPLIST_TAIL_OFFSET(zl));
742 p = ZIPLIST_ENTRY_HEAD(zl);
743 while(*p != ZIP_END) {
744 entry = zipEntry(p);
745 printf(
746 "{"
747 "addr 0x%08lx, "
748 "index %2d, "
749 "offset %5ld, "
750 "rl: %5u, "
751 "hs %2u, "
752 "pl: %5u, "
753 "pls: %2u, "
754 "payload %5u"
755 "} ",
756 (long unsigned int)p,
757 index,
758 p-zl,
759 entry.headersize+entry.len,
760 entry.headersize,
761 entry.prevrawlen,
762 entry.prevrawlensize,
763 entry.len);
764 p += entry.headersize;
765 if (ZIP_IS_STR(entry.encoding)) {
766 if (entry.len > 40) {
767 fwrite(p,40,1,stdout);
768 printf("...");
769 } else {
770 fwrite(p,entry.len,1,stdout);
771 }
772 } else {
773 printf("%lld", (long long) zipLoadInteger(p,entry.encoding));
774 }
775 printf("\n");
776 p += entry.len;
777 index++;
778 }
779 printf("{end}\n\n");
780}
781
782#ifdef ZIPLIST_TEST_MAIN
783#include <sys/time.h>
784
785unsigned char *createList() {
786 unsigned char *zl = ziplistNew();
787 zl = ziplistPush(zl, (unsigned char*)"foo", 3, ZIPLIST_TAIL);
788 zl = ziplistPush(zl, (unsigned char*)"quux", 4, ZIPLIST_TAIL);
789 zl = ziplistPush(zl, (unsigned char*)"hello", 5, ZIPLIST_HEAD);
790 zl = ziplistPush(zl, (unsigned char*)"1024", 4, ZIPLIST_TAIL);
791 return zl;
792}
793
794unsigned char *createIntList() {
795 unsigned char *zl = ziplistNew();
796 char buf[32];
797
798 sprintf(buf, "100");
799 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
800 sprintf(buf, "128000");
801 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
802 sprintf(buf, "-100");
803 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_HEAD);
804 sprintf(buf, "4294967296");
805 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_HEAD);
806 sprintf(buf, "non integer");
807 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
808 sprintf(buf, "much much longer non integer");
809 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), ZIPLIST_TAIL);
810 return zl;
811}
812
813long long usec(void) {
814 struct timeval tv;
815 gettimeofday(&tv,NULL);
816 return (((long long)tv.tv_sec)*1000000)+tv.tv_usec;
817}
818
819void stress(int pos, int num, int maxsize, int dnum) {
820 int i,j,k;
821 unsigned char *zl;
822 char posstr[2][5] = { "HEAD", "TAIL" };
823 long long start;
824 for (i = 0; i < maxsize; i+=dnum) {
825 zl = ziplistNew();
826 for (j = 0; j < i; j++) {
827 zl = ziplistPush(zl,(unsigned char*)"quux",4,ZIPLIST_TAIL);
828 }
829
830 /* Do num times a push+pop from pos */
831 start = usec();
832 for (k = 0; k < num; k++) {
833 zl = ziplistPush(zl,(unsigned char*)"quux",4,pos);
834 zl = ziplistDeleteRange(zl,0,1);
835 }
836 printf("List size: %8d, bytes: %8d, %dx push+pop (%s): %6lld usec\n",
837 i,ZIPLIST_BYTES(zl),num,posstr[pos],usec()-start);
838 zfree(zl);
839 }
840}
841
842void pop(unsigned char *zl, int where) {
843 unsigned char *p, *vstr;
844 unsigned int vlen;
845 long long vlong;
846
847 p = ziplistIndex(zl,where == ZIPLIST_HEAD ? 0 : -1);
848 if (ziplistGet(p,&vstr,&vlen,&vlong)) {
849 if (where == ZIPLIST_HEAD)
850 printf("Pop head: ");
851 else
852 printf("Pop tail: ");
853
854 if (vstr)
855 fwrite(vstr,vlen,1,stdout);
856 else
857 printf("%lld", vlong);
858
859 printf("\n");
860 ziplistDeleteRange(zl,-1,1);
861 } else {
862 printf("ERROR: Could not pop\n");
863 exit(1);
864 }
865}
866
867int main(int argc, char **argv) {
868 unsigned char *zl, *p;
869 unsigned char *entry;
870 unsigned int elen;
871 long long value;
872
873 /* If an argument is given, use it as the random seed. */
874 if (argc == 2)
875 srand(atoi(argv[1]));
876
877 zl = createIntList();
878 ziplistRepr(zl);
879
880 zl = createList();
881 ziplistRepr(zl);
882
883 pop(zl,ZIPLIST_TAIL);
884 ziplistRepr(zl);
885
886 pop(zl,ZIPLIST_HEAD);
887 ziplistRepr(zl);
888
889 pop(zl,ZIPLIST_TAIL);
890 ziplistRepr(zl);
891
892 pop(zl,ZIPLIST_TAIL);
893 ziplistRepr(zl);
894
895 printf("Get element at index 3:\n");
896 {
897 zl = createList();
898 p = ziplistIndex(zl, 3);
899 if (!ziplistGet(p, &entry, &elen, &value)) {
900 printf("ERROR: Could not access index 3\n");
901 return 1;
902 }
903 if (entry) {
904 fwrite(entry,elen,1,stdout);
905 printf("\n");
906 } else {
907 printf("%lld\n", value);
908 }
909 printf("\n");
910 }
911
912 printf("Get element at index 4 (out of range):\n");
913 {
914 zl = createList();
915 p = ziplistIndex(zl, 4);
916 if (p == NULL) {
917 printf("No entry\n");
918 } else {
919 printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p-zl);
920 return 1;
921 }
922 printf("\n");
923 }
924
925 printf("Get element at index -1 (last element):\n");
926 {
927 zl = createList();
928 p = ziplistIndex(zl, -1);
929 if (!ziplistGet(p, &entry, &elen, &value)) {
930 printf("ERROR: Could not access index -1\n");
931 return 1;
932 }
933 if (entry) {
934 fwrite(entry,elen,1,stdout);
935 printf("\n");
936 } else {
937 printf("%lld\n", value);
938 }
939 printf("\n");
940 }
941
942 printf("Get element at index -4 (first element):\n");
943 {
944 zl = createList();
945 p = ziplistIndex(zl, -4);
946 if (!ziplistGet(p, &entry, &elen, &value)) {
947 printf("ERROR: Could not access index -4\n");
948 return 1;
949 }
950 if (entry) {
951 fwrite(entry,elen,1,stdout);
952 printf("\n");
953 } else {
954 printf("%lld\n", value);
955 }
956 printf("\n");
957 }
958
959 printf("Get element at index -5 (reverse out of range):\n");
960 {
961 zl = createList();
962 p = ziplistIndex(zl, -5);
963 if (p == NULL) {
964 printf("No entry\n");
965 } else {
966 printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p-zl);
967 return 1;
968 }
969 printf("\n");
970 }
971
972 printf("Iterate list from 0 to end:\n");
973 {
974 zl = createList();
975 p = ziplistIndex(zl, 0);
976 while (ziplistGet(p, &entry, &elen, &value)) {
977 printf("Entry: ");
978 if (entry) {
979 fwrite(entry,elen,1,stdout);
980 } else {
981 printf("%lld", value);
982 }
983 p = ziplistNext(zl,p);
984 printf("\n");
985 }
986 printf("\n");
987 }
988
989 printf("Iterate list from 1 to end:\n");
990 {
991 zl = createList();
992 p = ziplistIndex(zl, 1);
993 while (ziplistGet(p, &entry, &elen, &value)) {
994 printf("Entry: ");
995 if (entry) {
996 fwrite(entry,elen,1,stdout);
997 } else {
998 printf("%lld", value);
999 }
1000 p = ziplistNext(zl,p);
1001 printf("\n");
1002 }
1003 printf("\n");
1004 }
1005
1006 printf("Iterate list from 2 to end:\n");
1007 {
1008 zl = createList();
1009 p = ziplistIndex(zl, 2);
1010 while (ziplistGet(p, &entry, &elen, &value)) {
1011 printf("Entry: ");
1012 if (entry) {
1013 fwrite(entry,elen,1,stdout);
1014 } else {
1015 printf("%lld", value);
1016 }
1017 p = ziplistNext(zl,p);
1018 printf("\n");
1019 }
1020 printf("\n");
1021 }
1022
1023 printf("Iterate starting out of range:\n");
1024 {
1025 zl = createList();
1026 p = ziplistIndex(zl, 4);
1027 if (!ziplistGet(p, &entry, &elen, &value)) {
1028 printf("No entry\n");
1029 } else {
1030 printf("ERROR\n");
1031 }
1032 printf("\n");
1033 }
1034
1035 printf("Iterate from back to front:\n");
1036 {
1037 zl = createList();
1038 p = ziplistIndex(zl, -1);
1039 while (ziplistGet(p, &entry, &elen, &value)) {
1040 printf("Entry: ");
1041 if (entry) {
1042 fwrite(entry,elen,1,stdout);
1043 } else {
1044 printf("%lld", value);
1045 }
1046 p = ziplistPrev(zl,p);
1047 printf("\n");
1048 }
1049 printf("\n");
1050 }
1051
1052 printf("Iterate from back to front, deleting all items:\n");
1053 {
1054 zl = createList();
1055 p = ziplistIndex(zl, -1);
1056 while (ziplistGet(p, &entry, &elen, &value)) {
1057 printf("Entry: ");
1058 if (entry) {
1059 fwrite(entry,elen,1,stdout);
1060 } else {
1061 printf("%lld", value);
1062 }
1063 zl = ziplistDelete(zl,&p);
1064 p = ziplistPrev(zl,p);
1065 printf("\n");
1066 }
1067 printf("\n");
1068 }
1069
1070 printf("Delete inclusive range 0,0:\n");
1071 {
1072 zl = createList();
1073 zl = ziplistDeleteRange(zl, 0, 1);
1074 ziplistRepr(zl);
1075 }
1076
1077 printf("Delete inclusive range 0,1:\n");
1078 {
1079 zl = createList();
1080 zl = ziplistDeleteRange(zl, 0, 2);
1081 ziplistRepr(zl);
1082 }
1083
1084 printf("Delete inclusive range 1,2:\n");
1085 {
1086 zl = createList();
1087 zl = ziplistDeleteRange(zl, 1, 2);
1088 ziplistRepr(zl);
1089 }
1090
1091 printf("Delete with start index out of range:\n");
1092 {
1093 zl = createList();
1094 zl = ziplistDeleteRange(zl, 5, 1);
1095 ziplistRepr(zl);
1096 }
1097
1098 printf("Delete with num overflow:\n");
1099 {
1100 zl = createList();
1101 zl = ziplistDeleteRange(zl, 1, 5);
1102 ziplistRepr(zl);
1103 }
1104
1105 printf("Delete foo while iterating:\n");
1106 {
1107 zl = createList();
1108 p = ziplistIndex(zl,0);
1109 while (ziplistGet(p,&entry,&elen,&value)) {
1110 if (entry && strncmp("foo",(char*)entry,elen) == 0) {
1111 printf("Delete foo\n");
1112 zl = ziplistDelete(zl,&p);
1113 } else {
1114 printf("Entry: ");
1115 if (entry) {
1116 fwrite(entry,elen,1,stdout);
1117 } else {
1118 printf("%lld",value);
1119 }
1120 p = ziplistNext(zl,p);
1121 printf("\n");
1122 }
1123 }
1124 printf("\n");
1125 ziplistRepr(zl);
1126 }
1127
1128 printf("Regression test for >255 byte strings:\n");
1129 {
1130 char v1[257],v2[257];
1131 memset(v1,'x',256);
1132 memset(v2,'y',256);
1133 zl = ziplistNew();
1134 zl = ziplistPush(zl,(unsigned char*)v1,strlen(v1),ZIPLIST_TAIL);
1135 zl = ziplistPush(zl,(unsigned char*)v2,strlen(v2),ZIPLIST_TAIL);
1136
1137 /* Pop values again and compare their value. */
1138 p = ziplistIndex(zl,0);
1139 assert(ziplistGet(p,&entry,&elen,&value));
1140 assert(strncmp(v1,entry,elen) == 0);
1141 p = ziplistIndex(zl,1);
1142 assert(ziplistGet(p,&entry,&elen,&value));
1143 assert(strncmp(v2,entry,elen) == 0);
1144 printf("SUCCESS\n\n");
1145 }
1146
1147 printf("Create long list and check indices:\n");
1148 {
1149 zl = ziplistNew();
1150 char buf[32];
1151 int i,len;
1152 for (i = 0; i < 1000; i++) {
1153 len = sprintf(buf,"%d",i);
1154 zl = ziplistPush(zl,(unsigned char*)buf,len,ZIPLIST_TAIL);
1155 }
1156 for (i = 0; i < 1000; i++) {
1157 p = ziplistIndex(zl,i);
1158 assert(ziplistGet(p,NULL,NULL,&value));
1159 assert(i == value);
1160
1161 p = ziplistIndex(zl,-i-1);
1162 assert(ziplistGet(p,NULL,NULL,&value));
1163 assert(999-i == value);
1164 }
1165 printf("SUCCESS\n\n");
1166 }
1167
1168 printf("Compare strings with ziplist entries:\n");
1169 {
1170 zl = createList();
1171 p = ziplistIndex(zl,0);
1172 if (!ziplistCompare(p,(unsigned char*)"hello",5)) {
1173 printf("ERROR: not \"hello\"\n");
1174 return 1;
1175 }
1176 if (ziplistCompare(p,(unsigned char*)"hella",5)) {
1177 printf("ERROR: \"hella\"\n");
1178 return 1;
1179 }
1180
1181 p = ziplistIndex(zl,3);
1182 if (!ziplistCompare(p,(unsigned char*)"1024",4)) {
1183 printf("ERROR: not \"1024\"\n");
1184 return 1;
1185 }
1186 if (ziplistCompare(p,(unsigned char*)"1025",4)) {
1187 printf("ERROR: \"1025\"\n");
1188 return 1;
1189 }
1190 printf("SUCCESS\n\n");
1191 }
1192
1193 printf("Stress with random payloads of different encoding:\n");
1194 {
1195 int i, idx, where, len;
1196 long long v;
1197 unsigned char *p;
1198 char buf[0x4041]; /* max length of generated string */
1199 zl = ziplistNew();
1200 for (i = 0; i < 100000; i++) {
1201 where = (rand() & 1) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
1202 if (rand() & 1) {
1203 /* equally likely create a 16, 32 or 64 bit int */
1204 v = (rand() & INT16_MAX) + ((1ll << 32) >> ((rand() % 3)*16));
1205 v *= 2*(rand() & 1)-1; /* randomly flip sign */
1206 sprintf(buf, "%lld", v);
1207 zl = ziplistPush(zl, (unsigned char*)buf, strlen(buf), where);
1208 } else {
1209 /* equally likely generate 6, 14 or >14 bit length */
1210 v = rand() & 0x3f;
1211 v += 0x4000 >> ((rand() % 3)*8);
1212 memset(buf, 'x', v);
1213 zl = ziplistPush(zl, (unsigned char*)buf, v, where);
1214 }
1215
1216 /* delete a random element */
1217 if ((len = ziplistLen(zl)) >= 10) {
1218 idx = rand() % len;
1219 // printf("Delete index %d\n", idx);
1220 // ziplistRepr(zl);
1221 ziplistDeleteRange(zl, idx, 1);
1222 // ziplistRepr(zl);
1223 len--;
1224 }
1225
1226 /* iterate from front to back */
1227 idx = 0;
1228 p = ziplistIndex(zl, 0);
1229 while((p = ziplistNext(zl,p)))
1230 idx++;
1231 assert(len == idx+1);
1232
1233 /* iterate from back to front */
1234 idx = 0;
1235 p = ziplistIndex(zl, -1);
1236 while((p = ziplistPrev(zl,p)))
1237 idx++;
1238 assert(len == idx+1);
1239 }
1240 printf("SUCCESS\n\n");
1241 }
1242
1243 printf("Stress with variable ziplist size:\n");
1244 {
1245 stress(ZIPLIST_HEAD,100000,16384,256);
1246 stress(ZIPLIST_TAIL,100000,16384,256);
1247 }
1248
1249 return 0;
1250}
1251
1252#endif