]>
git.saurik.com Git - redis.git/blob - src/ziplist.c
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.
9 * ----------------------------------------------------------------------------
11 * ZIPLIST OVERALL LAYOUT:
12 * The general layout of the ziplist is as follows:
13 * <zlbytes><zltail><zllen><entry><entry><zlend>
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.
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.
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.
25 * <zlend> is a single byte special value, equal to 255, which indicates the
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.
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.
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:
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.
56 * Integer encoded as int16_t (2 bytes).
58 * Integer encoded as int32_t (4 bytes).
60 * Integer encoded as int64_t (8 bytes).
62 * Integer encoded as 24 bit signed (3 bytes).
64 * All the integers are represented in little endian byte order.
76 #include "endianconv.h"
79 #define ZIP_BIGLEN 254
81 /* Different encoding/length possibilities */
82 #define ZIP_STR_MASK (0xc0)
83 #define ZIP_INT_MASK (0x30)
84 #define ZIP_STR_06B (0 << 6)
85 #define ZIP_STR_14B (1 << 6)
86 #define ZIP_STR_32B (2 << 6)
87 #define ZIP_INT_16B (0xc0 | 0<<4)
88 #define ZIP_INT_32B (0xc0 | 1<<4)
89 #define ZIP_INT_64B (0xc0 | 2<<4)
90 #define ZIP_INT_24B (0xc0 | 3<<4)
92 #define INT24_MAX 0x7fffff
93 #define INT24_MIN (-INT24_MAX - 1)
95 /* Macro to determine type */
96 #define ZIP_IS_STR(enc) (((enc) & ZIP_STR_MASK) < ZIP_STR_MASK)
99 #define ZIPLIST_BYTES(zl) (*((uint32_t*)(zl)))
100 #define ZIPLIST_TAIL_OFFSET(zl) (*((uint32_t*)((zl)+sizeof(uint32_t))))
101 #define ZIPLIST_LENGTH(zl) (*((uint16_t*)((zl)+sizeof(uint32_t)*2)))
102 #define ZIPLIST_HEADER_SIZE (sizeof(uint32_t)*2+sizeof(uint16_t))
103 #define ZIPLIST_ENTRY_HEAD(zl) ((zl)+ZIPLIST_HEADER_SIZE)
104 #define ZIPLIST_ENTRY_TAIL(zl) ((zl)+intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl)))
105 #define ZIPLIST_ENTRY_END(zl) ((zl)+intrev32ifbe(ZIPLIST_BYTES(zl))-1)
107 /* We know a positive increment can only be 1 because entries can only be
108 * pushed one at a time. */
109 #define ZIPLIST_INCR_LENGTH(zl,incr) { \
110 if (ZIPLIST_LENGTH(zl) < UINT16_MAX) \
111 ZIPLIST_LENGTH(zl) = intrev16ifbe(intrev16ifbe(ZIPLIST_LENGTH(zl))+incr); \
114 typedef struct zlentry
{
115 unsigned int prevrawlensize
, prevrawlen
;
116 unsigned int lensize
, len
;
117 unsigned int headersize
;
118 unsigned char encoding
;
122 #define ZIP_ENTRY_ENCODING(ptr, encoding) do { \
123 (encoding) = (ptr[0]) & (ZIP_STR_MASK | ZIP_INT_MASK); \
124 if (((encoding) & ZIP_STR_MASK) < ZIP_STR_MASK) { \
125 /* String encoding: 2 MSBs */ \
126 (encoding) &= ZIP_STR_MASK; \
130 /* Return bytes needed to store integer encoded by 'encoding' */
131 static unsigned int zipIntSize(unsigned char encoding
) {
133 case ZIP_INT_16B
: return sizeof(int16_t);
134 case ZIP_INT_24B
: return sizeof(int32_t)-sizeof(int8_t);
135 case ZIP_INT_32B
: return sizeof(int32_t);
136 case ZIP_INT_64B
: return sizeof(int64_t);
142 /* Encode the length 'l' writing it in 'p'. If p is NULL it just returns
143 * the amount of bytes required to encode such a length. */
144 static unsigned int zipEncodeLength(unsigned char *p
, unsigned char encoding
, unsigned int rawlen
) {
145 unsigned char len
= 1, buf
[5];
147 if (ZIP_IS_STR(encoding
)) {
148 /* Although encoding is given it may not be set for strings,
149 * so we determine it here using the raw length. */
150 if (rawlen
<= 0x3f) {
152 buf
[0] = ZIP_STR_06B
| rawlen
;
153 } else if (rawlen
<= 0x3fff) {
156 buf
[0] = ZIP_STR_14B
| ((rawlen
>> 8) & 0x3f);
157 buf
[1] = rawlen
& 0xff;
161 buf
[0] = ZIP_STR_32B
;
162 buf
[1] = (rawlen
>> 24) & 0xff;
163 buf
[2] = (rawlen
>> 16) & 0xff;
164 buf
[3] = (rawlen
>> 8) & 0xff;
165 buf
[4] = rawlen
& 0xff;
168 /* Implies integer encoding, so length is always 1. */
173 /* Store this length at p */
178 /* Decode the length encoded in 'ptr'. The 'encoding' variable will hold the
179 * entries encoding, the 'lensize' variable will hold the number of bytes
180 * required to encode the entries length, and the 'len' variable will hold the
182 #define ZIP_DECODE_LENGTH(ptr, encoding, lensize, len) do { \
183 ZIP_ENTRY_ENCODING((ptr), (encoding)); \
184 if ((encoding) < ZIP_STR_MASK) { \
185 if ((encoding) == ZIP_STR_06B) { \
187 (len) = (ptr)[0] & 0x3f; \
188 } else if ((encoding) == ZIP_STR_14B) { \
190 (len) = (((ptr)[0] & 0x3f) << 8) | (ptr)[1]; \
191 } else if (encoding == ZIP_STR_32B) { \
193 (len) = ((ptr)[1] << 24) | \
202 (len) = zipIntSize(encoding); \
206 /* Encode the length of the previous entry and write it to "p". Return the
207 * number of bytes needed to encode this length if "p" is NULL. */
208 static unsigned int zipPrevEncodeLength(unsigned char *p
, unsigned int len
) {
210 return (len
< ZIP_BIGLEN
) ? 1 : sizeof(len
)+1;
212 if (len
< ZIP_BIGLEN
) {
217 memcpy(p
+1,&len
,sizeof(len
));
219 return 1+sizeof(len
);
224 /* Encode the length of the previous entry and write it to "p". This only
225 * uses the larger encoding (required in __ziplistCascadeUpdate). */
226 static void zipPrevEncodeLengthForceLarge(unsigned char *p
, unsigned int len
) {
227 if (p
== NULL
) return;
229 memcpy(p
+1,&len
,sizeof(len
));
233 /* Decode the number of bytes required to store the length of the previous
234 * element, from the perspective of the entry pointed to by 'ptr'. */
235 #define ZIP_DECODE_PREVLENSIZE(ptr, prevlensize) do { \
236 if ((ptr)[0] < ZIP_BIGLEN) { \
243 /* Decode the length of the previous element, from the perspective of the entry
244 * pointed to by 'ptr'. */
245 #define ZIP_DECODE_PREVLEN(ptr, prevlensize, prevlen) do { \
246 ZIP_DECODE_PREVLENSIZE(ptr, prevlensize); \
247 if ((prevlensize) == 1) { \
248 (prevlen) = (ptr)[0]; \
249 } else if ((prevlensize) == 5) { \
250 assert(sizeof((prevlensize)) == 4); \
251 memcpy(&(prevlen), ((char*)(ptr)) + 1, 4); \
252 memrev32ifbe(&prevlen); \
256 /* Return the difference in number of bytes needed to store the length of the
257 * previous element 'len', in the entry pointed to by 'p'. */
258 static int zipPrevLenByteDiff(unsigned char *p
, unsigned int len
) {
259 unsigned int prevlensize
;
260 ZIP_DECODE_PREVLENSIZE(p
, prevlensize
);
261 return zipPrevEncodeLength(NULL
, len
) - prevlensize
;
264 /* Return the total number of bytes used by the entry pointed to by 'p'. */
265 static unsigned int zipRawEntryLength(unsigned char *p
) {
266 unsigned int prevlensize
, encoding
, lensize
, len
;
267 ZIP_DECODE_PREVLENSIZE(p
, prevlensize
);
268 ZIP_DECODE_LENGTH(p
+ prevlensize
, encoding
, lensize
, len
);
269 return prevlensize
+ lensize
+ len
;
272 /* Check if string pointed to by 'entry' can be encoded as an integer.
273 * Stores the integer value in 'v' and its encoding in 'encoding'. */
274 static int zipTryEncoding(unsigned char *entry
, unsigned int entrylen
, long long *v
, unsigned char *encoding
) {
277 if (entrylen
>= 32 || entrylen
== 0) return 0;
278 if (string2ll((char*)entry
,entrylen
,&value
)) {
279 /* Great, the string can be encoded. Check what's the smallest
280 * of our encoding types that can hold this value. */
281 if (value
>= INT16_MIN
&& value
<= INT16_MAX
) {
282 *encoding
= ZIP_INT_16B
;
283 } else if (value
>= INT24_MIN
&& value
<= INT24_MAX
) {
284 *encoding
= ZIP_INT_24B
;
285 } else if (value
>= INT32_MIN
&& value
<= INT32_MAX
) {
286 *encoding
= ZIP_INT_32B
;
288 *encoding
= ZIP_INT_64B
;
296 /* Store integer 'value' at 'p', encoded as 'encoding' */
297 static void zipSaveInteger(unsigned char *p
, int64_t value
, unsigned char encoding
) {
301 if (encoding
== ZIP_INT_16B
) {
303 memcpy(p
,&i16
,sizeof(i16
));
305 } else if (encoding
== ZIP_INT_24B
) {
308 memcpy(p
,((unsigned char*)&i32
)+1,sizeof(i32
)-sizeof(int8_t));
309 } else if (encoding
== ZIP_INT_32B
) {
311 memcpy(p
,&i32
,sizeof(i32
));
313 } else if (encoding
== ZIP_INT_64B
) {
315 memcpy(p
,&i64
,sizeof(i64
));
322 /* Read integer encoded as 'encoding' from 'p' */
323 static int64_t zipLoadInteger(unsigned char *p
, unsigned char encoding
) {
326 int64_t i64
, ret
= 0;
327 if (encoding
== ZIP_INT_16B
) {
328 memcpy(&i16
,p
,sizeof(i16
));
331 } else if (encoding
== ZIP_INT_32B
) {
332 memcpy(&i32
,p
,sizeof(i32
));
335 } else if (encoding
== ZIP_INT_24B
) {
337 memcpy(((unsigned char*)&i32
)+1,p
,sizeof(i32
)-sizeof(int8_t));
340 } else if (encoding
== ZIP_INT_64B
) {
341 memcpy(&i64
,p
,sizeof(i64
));
350 /* Return a struct with all information about an entry. */
351 static zlentry
zipEntry(unsigned char *p
) {
354 ZIP_DECODE_PREVLEN(p
, e
.prevrawlensize
, e
.prevrawlen
);
355 ZIP_DECODE_LENGTH(p
+ e
.prevrawlensize
, e
.encoding
, e
.lensize
, e
.len
);
356 e
.headersize
= e
.prevrawlensize
+ e
.lensize
;
361 /* Create a new empty ziplist. */
362 unsigned char *ziplistNew(void) {
363 unsigned int bytes
= ZIPLIST_HEADER_SIZE
+1;
364 unsigned char *zl
= zmalloc(bytes
);
365 ZIPLIST_BYTES(zl
) = intrev32ifbe(bytes
);
366 ZIPLIST_TAIL_OFFSET(zl
) = intrev32ifbe(ZIPLIST_HEADER_SIZE
);
367 ZIPLIST_LENGTH(zl
) = 0;
368 zl
[bytes
-1] = ZIP_END
;
372 /* Resize the ziplist. */
373 static unsigned char *ziplistResize(unsigned char *zl
, unsigned int len
) {
374 zl
= zrealloc(zl
,len
);
375 ZIPLIST_BYTES(zl
) = intrev32ifbe(len
);
380 /* When an entry is inserted, we need to set the prevlen field of the next
381 * entry to equal the length of the inserted entry. It can occur that this
382 * length cannot be encoded in 1 byte and the next entry needs to be grow
383 * a bit larger to hold the 5-byte encoded prevlen. This can be done for free,
384 * because this only happens when an entry is already being inserted (which
385 * causes a realloc and memmove). However, encoding the prevlen may require
386 * that this entry is grown as well. This effect may cascade throughout
387 * the ziplist when there are consecutive entries with a size close to
388 * ZIP_BIGLEN, so we need to check that the prevlen can be encoded in every
391 * Note that this effect can also happen in reverse, where the bytes required
392 * to encode the prevlen field can shrink. This effect is deliberately ignored,
393 * because it can cause a "flapping" effect where a chain prevlen fields is
394 * first grown and then shrunk again after consecutive inserts. Rather, the
395 * field is allowed to stay larger than necessary, because a large prevlen
396 * field implies the ziplist is holding large entries anyway.
398 * The pointer "p" points to the first entry that does NOT need to be
399 * updated, i.e. consecutive fields MAY need an update. */
400 static unsigned char *__ziplistCascadeUpdate(unsigned char *zl
, unsigned char *p
) {
401 size_t curlen
= intrev32ifbe(ZIPLIST_BYTES(zl
)), rawlen
, rawlensize
;
402 size_t offset
, noffset
, extra
;
406 while (p
[0] != ZIP_END
) {
408 rawlen
= cur
.headersize
+ cur
.len
;
409 rawlensize
= zipPrevEncodeLength(NULL
,rawlen
);
411 /* Abort if there is no next entry. */
412 if (p
[rawlen
] == ZIP_END
) break;
413 next
= zipEntry(p
+rawlen
);
415 /* Abort when "prevlen" has not changed. */
416 if (next
.prevrawlen
== rawlen
) break;
418 if (next
.prevrawlensize
< rawlensize
) {
419 /* The "prevlen" field of "next" needs more bytes to hold
420 * the raw length of "cur". */
422 extra
= rawlensize
-next
.prevrawlensize
;
423 zl
= ziplistResize(zl
,curlen
+extra
);
426 /* Current pointer and offset for next element. */
430 /* Update tail offset when next element is not the tail element. */
431 if ((zl
+intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
))) != np
) {
432 ZIPLIST_TAIL_OFFSET(zl
) =
433 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
))+extra
);
436 /* Move the tail to the back. */
437 memmove(np
+rawlensize
,
438 np
+next
.prevrawlensize
,
439 curlen
-noffset
-next
.prevrawlensize
-1);
440 zipPrevEncodeLength(np
,rawlen
);
442 /* Advance the cursor */
446 if (next
.prevrawlensize
> rawlensize
) {
447 /* This would result in shrinking, which we want to avoid.
448 * So, set "rawlen" in the available bytes. */
449 zipPrevEncodeLengthForceLarge(p
+rawlen
,rawlen
);
451 zipPrevEncodeLength(p
+rawlen
,rawlen
);
454 /* Stop here, as the raw length of "next" has not changed. */
461 /* Delete "num" entries, starting at "p". Returns pointer to the ziplist. */
462 static unsigned char *__ziplistDelete(unsigned char *zl
, unsigned char *p
, unsigned int num
) {
463 unsigned int i
, totlen
, deleted
= 0;
469 for (i
= 0; p
[0] != ZIP_END
&& i
< num
; i
++) {
470 p
+= zipRawEntryLength(p
);
476 if (p
[0] != ZIP_END
) {
477 /* Tricky: storing the prevlen in this entry might reduce or
478 * increase the number of bytes needed, compared to the current
479 * prevlen. Note that we can always store this length because
480 * it was previously stored by an entry that is being deleted. */
481 nextdiff
= zipPrevLenByteDiff(p
,first
.prevrawlen
);
482 zipPrevEncodeLength(p
-nextdiff
,first
.prevrawlen
);
484 /* Update offset for tail */
485 ZIPLIST_TAIL_OFFSET(zl
) =
486 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
))-totlen
);
488 /* When the tail contains more than one entry, we need to take
489 * "nextdiff" in account as well. Otherwise, a change in the
490 * size of prevlen doesn't have an effect on the *tail* offset. */
492 if (p
[tail
.headersize
+tail
.len
] != ZIP_END
) {
493 ZIPLIST_TAIL_OFFSET(zl
) =
494 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
))+nextdiff
);
497 /* Move tail to the front of the ziplist */
498 memmove(first
.p
,p
-nextdiff
,
499 intrev32ifbe(ZIPLIST_BYTES(zl
))-(p
-zl
)-1+nextdiff
);
501 /* The entire tail was deleted. No need to move memory. */
502 ZIPLIST_TAIL_OFFSET(zl
) =
503 intrev32ifbe((first
.p
-zl
)-first
.prevrawlen
);
506 /* Resize and update length */
508 zl
= ziplistResize(zl
, intrev32ifbe(ZIPLIST_BYTES(zl
))-totlen
+nextdiff
);
509 ZIPLIST_INCR_LENGTH(zl
,-deleted
);
512 /* When nextdiff != 0, the raw length of the next entry has changed, so
513 * we need to cascade the update throughout the ziplist */
515 zl
= __ziplistCascadeUpdate(zl
,p
);
520 /* Insert item at "p". */
521 static unsigned char *__ziplistInsert(unsigned char *zl
, unsigned char *p
, unsigned char *s
, unsigned int slen
) {
522 size_t curlen
= intrev32ifbe(ZIPLIST_BYTES(zl
)), reqlen
, prevlen
= 0;
525 unsigned char encoding
= 0;
526 long long value
= 123456789; /* initialized to avoid warning. Using a value
527 that is easy to see if for some reason
528 we use it uninitialized. */
531 /* Find out prevlen for the entry that is inserted. */
532 if (p
[0] != ZIP_END
) {
534 prevlen
= entry
.prevrawlen
;
536 unsigned char *ptail
= ZIPLIST_ENTRY_TAIL(zl
);
537 if (ptail
[0] != ZIP_END
) {
538 prevlen
= zipRawEntryLength(ptail
);
542 /* See if the entry can be encoded */
543 if (zipTryEncoding(s
,slen
,&value
,&encoding
)) {
544 /* 'encoding' is set to the appropriate integer encoding */
545 reqlen
= zipIntSize(encoding
);
547 /* 'encoding' is untouched, however zipEncodeLength will use the
548 * string length to figure out how to encode it. */
551 /* We need space for both the length of the previous entry and
552 * the length of the payload. */
553 reqlen
+= zipPrevEncodeLength(NULL
,prevlen
);
554 reqlen
+= zipEncodeLength(NULL
,encoding
,slen
);
556 /* When the insert position is not equal to the tail, we need to
557 * make sure that the next entry can hold this entry's length in
558 * its prevlen field. */
559 nextdiff
= (p
[0] != ZIP_END
) ? zipPrevLenByteDiff(p
,reqlen
) : 0;
561 /* Store offset because a realloc may change the address of zl. */
563 zl
= ziplistResize(zl
,curlen
+reqlen
+nextdiff
);
566 /* Apply memory move when necessary and update tail offset. */
567 if (p
[0] != ZIP_END
) {
568 /* Subtract one because of the ZIP_END bytes */
569 memmove(p
+reqlen
,p
-nextdiff
,curlen
-offset
-1+nextdiff
);
571 /* Encode this entry's raw length in the next entry. */
572 zipPrevEncodeLength(p
+reqlen
,reqlen
);
574 /* Update offset for tail */
575 ZIPLIST_TAIL_OFFSET(zl
) =
576 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
))+reqlen
);
578 /* When the tail contains more than one entry, we need to take
579 * "nextdiff" in account as well. Otherwise, a change in the
580 * size of prevlen doesn't have an effect on the *tail* offset. */
581 tail
= zipEntry(p
+reqlen
);
582 if (p
[reqlen
+tail
.headersize
+tail
.len
] != ZIP_END
) {
583 ZIPLIST_TAIL_OFFSET(zl
) =
584 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
))+nextdiff
);
587 /* This element will be the new tail. */
588 ZIPLIST_TAIL_OFFSET(zl
) = intrev32ifbe(p
-zl
);
591 /* When nextdiff != 0, the raw length of the next entry has changed, so
592 * we need to cascade the update throughout the ziplist */
595 zl
= __ziplistCascadeUpdate(zl
,p
+reqlen
);
599 /* Write the entry */
600 p
+= zipPrevEncodeLength(p
,prevlen
);
601 p
+= zipEncodeLength(p
,encoding
,slen
);
602 if (ZIP_IS_STR(encoding
)) {
605 zipSaveInteger(p
,value
,encoding
);
607 ZIPLIST_INCR_LENGTH(zl
,1);
611 unsigned char *ziplistPush(unsigned char *zl
, unsigned char *s
, unsigned int slen
, int where
) {
613 p
= (where
== ZIPLIST_HEAD
) ? ZIPLIST_ENTRY_HEAD(zl
) : ZIPLIST_ENTRY_END(zl
);
614 return __ziplistInsert(zl
,p
,s
,slen
);
617 /* Returns an offset to use for iterating with ziplistNext. When the given
618 * index is negative, the list is traversed back to front. When the list
619 * doesn't contain an element at the provided index, NULL is returned. */
620 unsigned char *ziplistIndex(unsigned char *zl
, int index
) {
625 p
= ZIPLIST_ENTRY_TAIL(zl
);
626 if (p
[0] != ZIP_END
) {
628 while (entry
.prevrawlen
> 0 && index
--) {
629 p
-= entry
.prevrawlen
;
634 p
= ZIPLIST_ENTRY_HEAD(zl
);
635 while (p
[0] != ZIP_END
&& index
--) {
636 p
+= zipRawEntryLength(p
);
639 return (p
[0] == ZIP_END
|| index
> 0) ? NULL
: p
;
642 /* Return pointer to next entry in ziplist.
644 * zl is the pointer to the ziplist
645 * p is the pointer to the current element
647 * The element after 'p' is returned, otherwise NULL if we are at the end. */
648 unsigned char *ziplistNext(unsigned char *zl
, unsigned char *p
) {
651 /* "p" could be equal to ZIP_END, caused by ziplistDelete,
652 * and we should return NULL. Otherwise, we should return NULL
653 * when the *next* element is ZIP_END (there is no next entry). */
654 if (p
[0] == ZIP_END
) {
658 p
+= zipRawEntryLength(p
);
659 if (p
[0] == ZIP_END
) {
666 /* Return pointer to previous entry in ziplist. */
667 unsigned char *ziplistPrev(unsigned char *zl
, unsigned char *p
) {
670 /* Iterating backwards from ZIP_END should return the tail. When "p" is
671 * equal to the first element of the list, we're already at the head,
672 * and should return NULL. */
673 if (p
[0] == ZIP_END
) {
674 p
= ZIPLIST_ENTRY_TAIL(zl
);
675 return (p
[0] == ZIP_END
) ? NULL
: p
;
676 } else if (p
== ZIPLIST_ENTRY_HEAD(zl
)) {
680 assert(entry
.prevrawlen
> 0);
681 return p
-entry
.prevrawlen
;
685 /* Get entry pointer to by 'p' and store in either 'e' or 'v' depending
686 * on the encoding of the entry. 'e' is always set to NULL to be able
687 * to find out whether the string pointer or the integer value was set.
688 * Return 0 if 'p' points to the end of the zipmap, 1 otherwise. */
689 unsigned int ziplistGet(unsigned char *p
, unsigned char **sstr
, unsigned int *slen
, long long *sval
) {
691 if (p
== NULL
|| p
[0] == ZIP_END
) return 0;
692 if (sstr
) *sstr
= NULL
;
695 if (ZIP_IS_STR(entry
.encoding
)) {
698 *sstr
= p
+entry
.headersize
;
702 *sval
= zipLoadInteger(p
+entry
.headersize
,entry
.encoding
);
708 /* Insert an entry at "p". */
709 unsigned char *ziplistInsert(unsigned char *zl
, unsigned char *p
, unsigned char *s
, unsigned int slen
) {
710 return __ziplistInsert(zl
,p
,s
,slen
);
713 /* Delete a single entry from the ziplist, pointed to by *p.
714 * Also update *p in place, to be able to iterate over the
715 * ziplist, while deleting entries. */
716 unsigned char *ziplistDelete(unsigned char *zl
, unsigned char **p
) {
717 size_t offset
= *p
-zl
;
718 zl
= __ziplistDelete(zl
,*p
,1);
720 /* Store pointer to current element in p, because ziplistDelete will
721 * do a realloc which might result in a different "zl"-pointer.
722 * When the delete direction is back to front, we might delete the last
723 * entry and end up with "p" pointing to ZIP_END, so check this. */
728 /* Delete a range of entries from the ziplist. */
729 unsigned char *ziplistDeleteRange(unsigned char *zl
, unsigned int index
, unsigned int num
) {
730 unsigned char *p
= ziplistIndex(zl
,index
);
731 return (p
== NULL
) ? zl
: __ziplistDelete(zl
,p
,num
);
734 /* Compare entry pointer to by 'p' with 'entry'. Return 1 if equal. */
735 unsigned int ziplistCompare(unsigned char *p
, unsigned char *sstr
, unsigned int slen
) {
737 unsigned char sencoding
;
738 long long zval
, sval
;
739 if (p
[0] == ZIP_END
) return 0;
742 if (ZIP_IS_STR(entry
.encoding
)) {
744 if (entry
.len
== slen
) {
745 return memcmp(p
+entry
.headersize
,sstr
,slen
) == 0;
750 /* Try to compare encoded values */
751 if (zipTryEncoding(sstr
,slen
,&sval
,&sencoding
)) {
752 if (entry
.encoding
== sencoding
) {
753 zval
= zipLoadInteger(p
+entry
.headersize
,entry
.encoding
);
761 /* Find pointer to the entry equal to the specified entry. Skip 'skip' entries
762 * between every comparison. Returns NULL when the field could not be found. */
763 unsigned char *ziplistFind(unsigned char *p
, unsigned char *vstr
, unsigned int vlen
, unsigned int skip
) {
765 unsigned char vencoding
= 0;
768 while (p
[0] != ZIP_END
) {
769 unsigned int prevlensize
, encoding
, lensize
, len
;
772 ZIP_DECODE_PREVLENSIZE(p
, prevlensize
);
773 ZIP_DECODE_LENGTH(p
+ prevlensize
, encoding
, lensize
, len
);
774 q
= p
+ prevlensize
+ lensize
;
777 /* Compare current entry with specified entry */
778 if (ZIP_IS_STR(encoding
)) {
779 if (len
== vlen
&& memcmp(q
, vstr
, vlen
) == 0) {
783 /* Find out if the specified entry can be encoded */
784 if (vencoding
== 0) {
785 /* UINT_MAX when the entry CANNOT be encoded */
786 if (!zipTryEncoding(vstr
, vlen
, &vll
, &vencoding
)) {
787 vencoding
= UCHAR_MAX
;
790 /* Must be non-zero by now */
794 /* Compare current entry with specified entry */
795 if (encoding
== vencoding
) {
796 long long ll
= zipLoadInteger(q
, encoding
);
803 /* Reset skip count */
810 /* Move to next entry */
817 /* Return length of ziplist. */
818 unsigned int ziplistLen(unsigned char *zl
) {
819 unsigned int len
= 0;
820 if (intrev16ifbe(ZIPLIST_LENGTH(zl
)) < UINT16_MAX
) {
821 len
= intrev16ifbe(ZIPLIST_LENGTH(zl
));
823 unsigned char *p
= zl
+ZIPLIST_HEADER_SIZE
;
824 while (*p
!= ZIP_END
) {
825 p
+= zipRawEntryLength(p
);
829 /* Re-store length if small enough */
830 if (len
< UINT16_MAX
) ZIPLIST_LENGTH(zl
) = intrev16ifbe(len
);
835 /* Return ziplist blob size in bytes. */
836 size_t ziplistBlobLen(unsigned char *zl
) {
837 return intrev32ifbe(ZIPLIST_BYTES(zl
));
840 void ziplistRepr(unsigned char *zl
) {
848 "{tail offset %u}\n",
849 intrev32ifbe(ZIPLIST_BYTES(zl
)),
850 intrev16ifbe(ZIPLIST_LENGTH(zl
)),
851 intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
)));
852 p
= ZIPLIST_ENTRY_HEAD(zl
);
853 while(*p
!= ZIP_END
) {
868 (unsigned long) (p
-zl
),
869 entry
.headersize
+entry
.len
,
872 entry
.prevrawlensize
,
874 p
+= entry
.headersize
;
875 if (ZIP_IS_STR(entry
.encoding
)) {
876 if (entry
.len
> 40) {
877 if (fwrite(p
,40,1,stdout
) == 0) perror("fwrite");
881 fwrite(p
,entry
.len
,1,stdout
) == 0) perror("fwrite");
884 printf("%lld", (long long) zipLoadInteger(p
,entry
.encoding
));
893 #ifdef ZIPLIST_TEST_MAIN
894 #include <sys/time.h>
898 #define debug(f, ...) { if (DEBUG) printf(f, __VA_ARGS__); }
900 unsigned char *createList() {
901 unsigned char *zl
= ziplistNew();
902 zl
= ziplistPush(zl
, (unsigned char*)"foo", 3, ZIPLIST_TAIL
);
903 zl
= ziplistPush(zl
, (unsigned char*)"quux", 4, ZIPLIST_TAIL
);
904 zl
= ziplistPush(zl
, (unsigned char*)"hello", 5, ZIPLIST_HEAD
);
905 zl
= ziplistPush(zl
, (unsigned char*)"1024", 4, ZIPLIST_TAIL
);
909 unsigned char *createIntList() {
910 unsigned char *zl
= ziplistNew();
914 zl
= ziplistPush(zl
, (unsigned char*)buf
, strlen(buf
), ZIPLIST_TAIL
);
915 sprintf(buf
, "128000");
916 zl
= ziplistPush(zl
, (unsigned char*)buf
, strlen(buf
), ZIPLIST_TAIL
);
917 sprintf(buf
, "-100");
918 zl
= ziplistPush(zl
, (unsigned char*)buf
, strlen(buf
), ZIPLIST_HEAD
);
919 sprintf(buf
, "4294967296");
920 zl
= ziplistPush(zl
, (unsigned char*)buf
, strlen(buf
), ZIPLIST_HEAD
);
921 sprintf(buf
, "non integer");
922 zl
= ziplistPush(zl
, (unsigned char*)buf
, strlen(buf
), ZIPLIST_TAIL
);
923 sprintf(buf
, "much much longer non integer");
924 zl
= ziplistPush(zl
, (unsigned char*)buf
, strlen(buf
), ZIPLIST_TAIL
);
928 long long usec(void) {
930 gettimeofday(&tv
,NULL
);
931 return (((long long)tv
.tv_sec
)*1000000)+tv
.tv_usec
;
934 void stress(int pos
, int num
, int maxsize
, int dnum
) {
937 char posstr
[2][5] = { "HEAD", "TAIL" };
939 for (i
= 0; i
< maxsize
; i
+=dnum
) {
941 for (j
= 0; j
< i
; j
++) {
942 zl
= ziplistPush(zl
,(unsigned char*)"quux",4,ZIPLIST_TAIL
);
945 /* Do num times a push+pop from pos */
947 for (k
= 0; k
< num
; k
++) {
948 zl
= ziplistPush(zl
,(unsigned char*)"quux",4,pos
);
949 zl
= ziplistDeleteRange(zl
,0,1);
951 printf("List size: %8d, bytes: %8d, %dx push+pop (%s): %6lld usec\n",
952 i
,intrev32ifbe(ZIPLIST_BYTES(zl
)),num
,posstr
[pos
],usec()-start
);
957 void pop(unsigned char *zl
, int where
) {
958 unsigned char *p
, *vstr
;
962 p
= ziplistIndex(zl
,where
== ZIPLIST_HEAD
? 0 : -1);
963 if (ziplistGet(p
,&vstr
,&vlen
,&vlong
)) {
964 if (where
== ZIPLIST_HEAD
)
965 printf("Pop head: ");
967 printf("Pop tail: ");
970 if (vlen
&& fwrite(vstr
,vlen
,1,stdout
) == 0) perror("fwrite");
972 printf("%lld", vlong
);
975 ziplistDeleteRange(zl
,-1,1);
977 printf("ERROR: Could not pop\n");
982 int randstring(char *target
, unsigned int min
, unsigned int max
) {
983 int p
, len
= min
+rand()%(max
-min
+1);
1003 target
[p
++] = minval
+rand()%(maxval
-minval
+1);
1007 int main(int argc
, char **argv
) {
1008 unsigned char *zl
, *p
;
1009 unsigned char *entry
;
1013 /* If an argument is given, use it as the random seed. */
1015 srand(atoi(argv
[1]));
1017 zl
= createIntList();
1023 pop(zl
,ZIPLIST_TAIL
);
1026 pop(zl
,ZIPLIST_HEAD
);
1029 pop(zl
,ZIPLIST_TAIL
);
1032 pop(zl
,ZIPLIST_TAIL
);
1035 printf("Get element at index 3:\n");
1038 p
= ziplistIndex(zl
, 3);
1039 if (!ziplistGet(p
, &entry
, &elen
, &value
)) {
1040 printf("ERROR: Could not access index 3\n");
1044 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1047 printf("%lld\n", value
);
1052 printf("Get element at index 4 (out of range):\n");
1055 p
= ziplistIndex(zl
, 4);
1057 printf("No entry\n");
1059 printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p
-zl
);
1065 printf("Get element at index -1 (last element):\n");
1068 p
= ziplistIndex(zl
, -1);
1069 if (!ziplistGet(p
, &entry
, &elen
, &value
)) {
1070 printf("ERROR: Could not access index -1\n");
1074 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1077 printf("%lld\n", value
);
1082 printf("Get element at index -4 (first element):\n");
1085 p
= ziplistIndex(zl
, -4);
1086 if (!ziplistGet(p
, &entry
, &elen
, &value
)) {
1087 printf("ERROR: Could not access index -4\n");
1091 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1094 printf("%lld\n", value
);
1099 printf("Get element at index -5 (reverse out of range):\n");
1102 p
= ziplistIndex(zl
, -5);
1104 printf("No entry\n");
1106 printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p
-zl
);
1112 printf("Iterate list from 0 to end:\n");
1115 p
= ziplistIndex(zl
, 0);
1116 while (ziplistGet(p
, &entry
, &elen
, &value
)) {
1119 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1121 printf("%lld", value
);
1123 p
= ziplistNext(zl
,p
);
1129 printf("Iterate list from 1 to end:\n");
1132 p
= ziplistIndex(zl
, 1);
1133 while (ziplistGet(p
, &entry
, &elen
, &value
)) {
1136 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1138 printf("%lld", value
);
1140 p
= ziplistNext(zl
,p
);
1146 printf("Iterate list from 2 to end:\n");
1149 p
= ziplistIndex(zl
, 2);
1150 while (ziplistGet(p
, &entry
, &elen
, &value
)) {
1153 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1155 printf("%lld", value
);
1157 p
= ziplistNext(zl
,p
);
1163 printf("Iterate starting out of range:\n");
1166 p
= ziplistIndex(zl
, 4);
1167 if (!ziplistGet(p
, &entry
, &elen
, &value
)) {
1168 printf("No entry\n");
1175 printf("Iterate from back to front:\n");
1178 p
= ziplistIndex(zl
, -1);
1179 while (ziplistGet(p
, &entry
, &elen
, &value
)) {
1182 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1184 printf("%lld", value
);
1186 p
= ziplistPrev(zl
,p
);
1192 printf("Iterate from back to front, deleting all items:\n");
1195 p
= ziplistIndex(zl
, -1);
1196 while (ziplistGet(p
, &entry
, &elen
, &value
)) {
1199 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1201 printf("%lld", value
);
1203 zl
= ziplistDelete(zl
,&p
);
1204 p
= ziplistPrev(zl
,p
);
1210 printf("Delete inclusive range 0,0:\n");
1213 zl
= ziplistDeleteRange(zl
, 0, 1);
1217 printf("Delete inclusive range 0,1:\n");
1220 zl
= ziplistDeleteRange(zl
, 0, 2);
1224 printf("Delete inclusive range 1,2:\n");
1227 zl
= ziplistDeleteRange(zl
, 1, 2);
1231 printf("Delete with start index out of range:\n");
1234 zl
= ziplistDeleteRange(zl
, 5, 1);
1238 printf("Delete with num overflow:\n");
1241 zl
= ziplistDeleteRange(zl
, 1, 5);
1245 printf("Delete foo while iterating:\n");
1248 p
= ziplistIndex(zl
,0);
1249 while (ziplistGet(p
,&entry
,&elen
,&value
)) {
1250 if (entry
&& strncmp("foo",(char*)entry
,elen
) == 0) {
1251 printf("Delete foo\n");
1252 zl
= ziplistDelete(zl
,&p
);
1256 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0)
1259 printf("%lld",value
);
1261 p
= ziplistNext(zl
,p
);
1269 printf("Regression test for >255 byte strings:\n");
1271 char v1
[257],v2
[257];
1275 zl
= ziplistPush(zl
,(unsigned char*)v1
,strlen(v1
),ZIPLIST_TAIL
);
1276 zl
= ziplistPush(zl
,(unsigned char*)v2
,strlen(v2
),ZIPLIST_TAIL
);
1278 /* Pop values again and compare their value. */
1279 p
= ziplistIndex(zl
,0);
1280 assert(ziplistGet(p
,&entry
,&elen
,&value
));
1281 assert(strncmp(v1
,(char*)entry
,elen
) == 0);
1282 p
= ziplistIndex(zl
,1);
1283 assert(ziplistGet(p
,&entry
,&elen
,&value
));
1284 assert(strncmp(v2
,(char*)entry
,elen
) == 0);
1285 printf("SUCCESS\n\n");
1288 printf("Create long list and check indices:\n");
1293 for (i
= 0; i
< 1000; i
++) {
1294 len
= sprintf(buf
,"%d",i
);
1295 zl
= ziplistPush(zl
,(unsigned char*)buf
,len
,ZIPLIST_TAIL
);
1297 for (i
= 0; i
< 1000; i
++) {
1298 p
= ziplistIndex(zl
,i
);
1299 assert(ziplistGet(p
,NULL
,NULL
,&value
));
1302 p
= ziplistIndex(zl
,-i
-1);
1303 assert(ziplistGet(p
,NULL
,NULL
,&value
));
1304 assert(999-i
== value
);
1306 printf("SUCCESS\n\n");
1309 printf("Compare strings with ziplist entries:\n");
1312 p
= ziplistIndex(zl
,0);
1313 if (!ziplistCompare(p
,(unsigned char*)"hello",5)) {
1314 printf("ERROR: not \"hello\"\n");
1317 if (ziplistCompare(p
,(unsigned char*)"hella",5)) {
1318 printf("ERROR: \"hella\"\n");
1322 p
= ziplistIndex(zl
,3);
1323 if (!ziplistCompare(p
,(unsigned char*)"1024",4)) {
1324 printf("ERROR: not \"1024\"\n");
1327 if (ziplistCompare(p
,(unsigned char*)"1025",4)) {
1328 printf("ERROR: \"1025\"\n");
1331 printf("SUCCESS\n\n");
1334 printf("Stress with random payloads of different encoding:\n");
1343 /* Hold temp vars from ziplist */
1344 unsigned char *sstr
;
1348 for (i
= 0; i
< 20000; i
++) {
1351 listSetFreeMethod(ref
,sdsfree
);
1355 for (j
= 0; j
< len
; j
++) {
1356 where
= (rand() & 1) ? ZIPLIST_HEAD
: ZIPLIST_TAIL
;
1358 buflen
= randstring(buf
,1,sizeof(buf
)-1);
1360 switch(rand() % 3) {
1362 buflen
= sprintf(buf
,"%lld",(0LL + rand()) >> 20);
1365 buflen
= sprintf(buf
,"%lld",(0LL + rand()));
1368 buflen
= sprintf(buf
,"%lld",(0LL + rand()) << 20);
1375 /* Add to ziplist */
1376 zl
= ziplistPush(zl
, (unsigned char*)buf
, buflen
, where
);
1378 /* Add to reference list */
1379 if (where
== ZIPLIST_HEAD
) {
1380 listAddNodeHead(ref
,sdsnewlen(buf
, buflen
));
1381 } else if (where
== ZIPLIST_TAIL
) {
1382 listAddNodeTail(ref
,sdsnewlen(buf
, buflen
));
1388 assert(listLength(ref
) == ziplistLen(zl
));
1389 for (j
= 0; j
< len
; j
++) {
1390 /* Naive way to get elements, but similar to the stresser
1391 * executed from the Tcl test suite. */
1392 p
= ziplistIndex(zl
,j
);
1393 refnode
= listIndex(ref
,j
);
1395 assert(ziplistGet(p
,&sstr
,&slen
,&sval
));
1397 buflen
= sprintf(buf
,"%lld",sval
);
1400 memcpy(buf
,sstr
,buflen
);
1403 assert(memcmp(buf
,listNodeValue(refnode
),buflen
) == 0);
1408 printf("SUCCESS\n\n");
1411 printf("Stress with variable ziplist size:\n");
1413 stress(ZIPLIST_HEAD
,100000,16384,256);
1414 stress(ZIPLIST_TAIL
,100000,16384,256);