]>
git.saurik.com Git - redis.git/blob - src/ziplist.c
a2c0edb3a1cf74c088c6f7e2b8e46959e7695d45
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).
72 #include "endianconv.h"
75 #define ZIP_BIGLEN 254
77 /* Different encoding/length possibilities */
78 #define ZIP_STR_MASK (0xc0)
79 #define ZIP_INT_MASK (0x30)
80 #define ZIP_STR_06B (0 << 6)
81 #define ZIP_STR_14B (1 << 6)
82 #define ZIP_STR_32B (2 << 6)
83 #define ZIP_INT_16B (0xc0 | 0<<4)
84 #define ZIP_INT_32B (0xc0 | 1<<4)
85 #define ZIP_INT_64B (0xc0 | 2<<4)
86 #define ZIP_INT_24B (0xc0 | 3<<4)
88 #define INT24_MAX 0x7fffff
89 #define INT24_MIN (-INT24_MAX - 1)
91 /* Macro to determine type */
92 #define ZIP_IS_STR(enc) (((enc) & ZIP_STR_MASK) < ZIP_STR_MASK)
95 #define ZIPLIST_BYTES(zl) (*((uint32_t*)(zl)))
96 #define ZIPLIST_TAIL_OFFSET(zl) (*((uint32_t*)((zl)+sizeof(uint32_t))))
97 #define ZIPLIST_LENGTH(zl) (*((uint16_t*)((zl)+sizeof(uint32_t)*2)))
98 #define ZIPLIST_HEADER_SIZE (sizeof(uint32_t)*2+sizeof(uint16_t))
99 #define ZIPLIST_ENTRY_HEAD(zl) ((zl)+ZIPLIST_HEADER_SIZE)
100 #define ZIPLIST_ENTRY_TAIL(zl) ((zl)+intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl)))
101 #define ZIPLIST_ENTRY_END(zl) ((zl)+intrev32ifbe(ZIPLIST_BYTES(zl))-1)
103 /* We know a positive increment can only be 1 because entries can only be
104 * pushed one at a time. */
105 #define ZIPLIST_INCR_LENGTH(zl,incr) { \
106 if (ZIPLIST_LENGTH(zl) < UINT16_MAX) \
107 ZIPLIST_LENGTH(zl) = intrev16ifbe(intrev16ifbe(ZIPLIST_LENGTH(zl))+incr); \
110 typedef struct zlentry
{
111 unsigned int prevrawlensize
, prevrawlen
;
112 unsigned int lensize
, len
;
113 unsigned int headersize
;
114 unsigned char encoding
;
118 #define ZIP_ENTRY_ENCODING(ptr, encoding) do { \
119 (encoding) = (ptr[0]) & (ZIP_STR_MASK | ZIP_INT_MASK); \
120 if (((encoding) & ZIP_STR_MASK) < ZIP_STR_MASK) { \
121 /* String encoding: 2 MSBs */ \
122 (encoding) &= ZIP_STR_MASK; \
126 /* Return bytes needed to store integer encoded by 'encoding' */
127 static unsigned int zipIntSize(unsigned char encoding
) {
129 case ZIP_INT_16B
: return sizeof(int16_t);
130 case ZIP_INT_24B
: return sizeof(int32_t)-sizeof(int8_t);
131 case ZIP_INT_32B
: return sizeof(int32_t);
132 case ZIP_INT_64B
: return sizeof(int64_t);
138 /* Encode the length 'l' writing it in 'p'. If p is NULL it just returns
139 * the amount of bytes required to encode such a length. */
140 static unsigned int zipEncodeLength(unsigned char *p
, unsigned char encoding
, unsigned int rawlen
) {
141 unsigned char len
= 1, buf
[5];
143 if (ZIP_IS_STR(encoding
)) {
144 /* Although encoding is given it may not be set for strings,
145 * so we determine it here using the raw length. */
146 if (rawlen
<= 0x3f) {
148 buf
[0] = ZIP_STR_06B
| rawlen
;
149 } else if (rawlen
<= 0x3fff) {
152 buf
[0] = ZIP_STR_14B
| ((rawlen
>> 8) & 0x3f);
153 buf
[1] = rawlen
& 0xff;
157 buf
[0] = ZIP_STR_32B
;
158 buf
[1] = (rawlen
>> 24) & 0xff;
159 buf
[2] = (rawlen
>> 16) & 0xff;
160 buf
[3] = (rawlen
>> 8) & 0xff;
161 buf
[4] = rawlen
& 0xff;
164 /* Implies integer encoding, so length is always 1. */
169 /* Store this length at p */
174 /* Decode the length encoded in 'ptr'. The 'encoding' variable will hold the
175 * entries encoding, the 'lensize' variable will hold the number of bytes
176 * required to encode the entries length, and the 'len' variable will hold the
178 #define ZIP_DECODE_LENGTH(ptr, encoding, lensize, len) do { \
179 ZIP_ENTRY_ENCODING((ptr), (encoding)); \
180 if ((encoding) < ZIP_STR_MASK) { \
181 if ((encoding) == ZIP_STR_06B) { \
183 (len) = (ptr)[0] & 0x3f; \
184 } else if ((encoding) == ZIP_STR_14B) { \
186 (len) = (((ptr)[0] & 0x3f) << 8) | (ptr)[1]; \
187 } else if (encoding == ZIP_STR_32B) { \
189 (len) = ((ptr)[1] << 24) | \
198 (len) = zipIntSize(encoding); \
202 /* Encode the length of the previous entry and write it to "p". Return the
203 * number of bytes needed to encode this length if "p" is NULL. */
204 static unsigned int zipPrevEncodeLength(unsigned char *p
, unsigned int len
) {
206 return (len
< ZIP_BIGLEN
) ? 1 : sizeof(len
)+1;
208 if (len
< ZIP_BIGLEN
) {
213 memcpy(p
+1,&len
,sizeof(len
));
215 return 1+sizeof(len
);
220 /* Encode the length of the previous entry and write it to "p". This only
221 * uses the larger encoding (required in __ziplistCascadeUpdate). */
222 static void zipPrevEncodeLengthForceLarge(unsigned char *p
, unsigned int len
) {
223 if (p
== NULL
) return;
225 memcpy(p
+1,&len
,sizeof(len
));
229 /* Decode the number of bytes required to store the length of the previous
230 * element, from the perspective of the entry pointed to by 'ptr'. */
231 #define ZIP_DECODE_PREVLENSIZE(ptr, prevlensize) do { \
232 if ((ptr)[0] < ZIP_BIGLEN) { \
239 /* Decode the length of the previous element, from the perspective of the entry
240 * pointed to by 'ptr'. */
241 #define ZIP_DECODE_PREVLEN(ptr, prevlensize, prevlen) do { \
242 ZIP_DECODE_PREVLENSIZE(ptr, prevlensize); \
243 if ((prevlensize) == 1) { \
244 (prevlen) = (ptr)[0]; \
245 } else if ((prevlensize) == 5) { \
246 assert(sizeof((prevlensize)) == 4); \
247 memcpy(&(prevlen), ((char*)(ptr)) + 1, 4); \
248 memrev32ifbe(&prevlen); \
252 /* Return the difference in number of bytes needed to store the length of the
253 * previous element 'len', in the entry pointed to by 'p'. */
254 static int zipPrevLenByteDiff(unsigned char *p
, unsigned int len
) {
255 unsigned int prevlensize
;
256 ZIP_DECODE_PREVLENSIZE(p
, prevlensize
);
257 return zipPrevEncodeLength(NULL
, len
) - prevlensize
;
260 /* Return the total number of bytes used by the entry pointed to by 'p'. */
261 static unsigned int zipRawEntryLength(unsigned char *p
) {
262 unsigned int prevlensize
, encoding
, lensize
, len
;
263 ZIP_DECODE_PREVLENSIZE(p
, prevlensize
);
264 ZIP_DECODE_LENGTH(p
+ prevlensize
, encoding
, lensize
, len
);
265 return prevlensize
+ lensize
+ len
;
268 /* Check if string pointed to by 'entry' can be encoded as an integer.
269 * Stores the integer value in 'v' and its encoding in 'encoding'. */
270 static int zipTryEncoding(unsigned char *entry
, unsigned int entrylen
, long long *v
, unsigned char *encoding
) {
273 if (entrylen
>= 32 || entrylen
== 0) return 0;
274 if (string2ll((char*)entry
,entrylen
,&value
)) {
275 /* Great, the string can be encoded. Check what's the smallest
276 * of our encoding types that can hold this value. */
277 if (value
>= INT16_MIN
&& value
<= INT16_MAX
) {
278 *encoding
= ZIP_INT_16B
;
279 } else if (value
>= INT24_MIN
&& value
<= INT24_MAX
) {
280 *encoding
= ZIP_INT_24B
;
281 } else if (value
>= INT32_MIN
&& value
<= INT32_MAX
) {
282 *encoding
= ZIP_INT_32B
;
284 *encoding
= ZIP_INT_64B
;
292 /* Store integer 'value' at 'p', encoded as 'encoding' */
293 static void zipSaveInteger(unsigned char *p
, int64_t value
, unsigned char encoding
) {
297 if (encoding
== ZIP_INT_16B
) {
299 memcpy(p
,&i16
,sizeof(i16
));
301 } else if (encoding
== ZIP_INT_24B
) {
304 memcpy(p
,((unsigned char*)&i32
)+1,sizeof(i32
)-sizeof(int8_t));
305 } else if (encoding
== ZIP_INT_32B
) {
307 memcpy(p
,&i32
,sizeof(i32
));
309 } else if (encoding
== ZIP_INT_64B
) {
311 memcpy(p
,&i64
,sizeof(i64
));
318 /* Read integer encoded as 'encoding' from 'p' */
319 static int64_t zipLoadInteger(unsigned char *p
, unsigned char encoding
) {
322 int64_t i64
, ret
= 0;
323 if (encoding
== ZIP_INT_16B
) {
324 memcpy(&i16
,p
,sizeof(i16
));
327 } else if (encoding
== ZIP_INT_32B
) {
328 memcpy(&i32
,p
,sizeof(i32
));
331 } else if (encoding
== ZIP_INT_24B
) {
333 memcpy(((unsigned char*)&i32
)+1,p
,sizeof(i32
)-sizeof(int8_t));
336 } else if (encoding
== ZIP_INT_64B
) {
337 memcpy(&i64
,p
,sizeof(i64
));
346 /* Return a struct with all information about an entry. */
347 static zlentry
zipEntry(unsigned char *p
) {
350 ZIP_DECODE_PREVLEN(p
, e
.prevrawlensize
, e
.prevrawlen
);
351 ZIP_DECODE_LENGTH(p
+ e
.prevrawlensize
, e
.encoding
, e
.lensize
, e
.len
);
352 e
.headersize
= e
.prevrawlensize
+ e
.lensize
;
357 /* Create a new empty ziplist. */
358 unsigned char *ziplistNew(void) {
359 unsigned int bytes
= ZIPLIST_HEADER_SIZE
+1;
360 unsigned char *zl
= zmalloc(bytes
);
361 ZIPLIST_BYTES(zl
) = intrev32ifbe(bytes
);
362 ZIPLIST_TAIL_OFFSET(zl
) = intrev32ifbe(ZIPLIST_HEADER_SIZE
);
363 ZIPLIST_LENGTH(zl
) = 0;
364 zl
[bytes
-1] = ZIP_END
;
368 /* Resize the ziplist. */
369 static unsigned char *ziplistResize(unsigned char *zl
, unsigned int len
) {
370 zl
= zrealloc(zl
,len
);
371 ZIPLIST_BYTES(zl
) = intrev32ifbe(len
);
376 /* When an entry is inserted, we need to set the prevlen field of the next
377 * entry to equal the length of the inserted entry. It can occur that this
378 * length cannot be encoded in 1 byte and the next entry needs to be grow
379 * a bit larger to hold the 5-byte encoded prevlen. This can be done for free,
380 * because this only happens when an entry is already being inserted (which
381 * causes a realloc and memmove). However, encoding the prevlen may require
382 * that this entry is grown as well. This effect may cascade throughout
383 * the ziplist when there are consecutive entries with a size close to
384 * ZIP_BIGLEN, so we need to check that the prevlen can be encoded in every
387 * Note that this effect can also happen in reverse, where the bytes required
388 * to encode the prevlen field can shrink. This effect is deliberately ignored,
389 * because it can cause a "flapping" effect where a chain prevlen fields is
390 * first grown and then shrunk again after consecutive inserts. Rather, the
391 * field is allowed to stay larger than necessary, because a large prevlen
392 * field implies the ziplist is holding large entries anyway.
394 * The pointer "p" points to the first entry that does NOT need to be
395 * updated, i.e. consecutive fields MAY need an update. */
396 static unsigned char *__ziplistCascadeUpdate(unsigned char *zl
, unsigned char *p
) {
397 size_t curlen
= intrev32ifbe(ZIPLIST_BYTES(zl
)), rawlen
, rawlensize
;
398 size_t offset
, noffset
, extra
;
402 while (p
[0] != ZIP_END
) {
404 rawlen
= cur
.headersize
+ cur
.len
;
405 rawlensize
= zipPrevEncodeLength(NULL
,rawlen
);
407 /* Abort if there is no next entry. */
408 if (p
[rawlen
] == ZIP_END
) break;
409 next
= zipEntry(p
+rawlen
);
411 /* Abort when "prevlen" has not changed. */
412 if (next
.prevrawlen
== rawlen
) break;
414 if (next
.prevrawlensize
< rawlensize
) {
415 /* The "prevlen" field of "next" needs more bytes to hold
416 * the raw length of "cur". */
418 extra
= rawlensize
-next
.prevrawlensize
;
419 zl
= ziplistResize(zl
,curlen
+extra
);
422 /* Current pointer and offset for next element. */
426 /* Update tail offset when next element is not the tail element. */
427 if ((zl
+intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
))) != np
) {
428 ZIPLIST_TAIL_OFFSET(zl
) =
429 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
))+extra
);
432 /* Move the tail to the back. */
433 memmove(np
+rawlensize
,
434 np
+next
.prevrawlensize
,
435 curlen
-noffset
-next
.prevrawlensize
-1);
436 zipPrevEncodeLength(np
,rawlen
);
438 /* Advance the cursor */
442 if (next
.prevrawlensize
> rawlensize
) {
443 /* This would result in shrinking, which we want to avoid.
444 * So, set "rawlen" in the available bytes. */
445 zipPrevEncodeLengthForceLarge(p
+rawlen
,rawlen
);
447 zipPrevEncodeLength(p
+rawlen
,rawlen
);
450 /* Stop here, as the raw length of "next" has not changed. */
457 /* Delete "num" entries, starting at "p". Returns pointer to the ziplist. */
458 static unsigned char *__ziplistDelete(unsigned char *zl
, unsigned char *p
, unsigned int num
) {
459 unsigned int i
, totlen
, deleted
= 0;
465 for (i
= 0; p
[0] != ZIP_END
&& i
< num
; i
++) {
466 p
+= zipRawEntryLength(p
);
472 if (p
[0] != ZIP_END
) {
473 /* Tricky: storing the prevlen in this entry might reduce or
474 * increase the number of bytes needed, compared to the current
475 * prevlen. Note that we can always store this length because
476 * it was previously stored by an entry that is being deleted. */
477 nextdiff
= zipPrevLenByteDiff(p
,first
.prevrawlen
);
478 zipPrevEncodeLength(p
-nextdiff
,first
.prevrawlen
);
480 /* Update offset for tail */
481 ZIPLIST_TAIL_OFFSET(zl
) =
482 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
))-totlen
);
484 /* When the tail contains more than one entry, we need to take
485 * "nextdiff" in account as well. Otherwise, a change in the
486 * size of prevlen doesn't have an effect on the *tail* offset. */
488 if (p
[tail
.headersize
+tail
.len
] != ZIP_END
) {
489 ZIPLIST_TAIL_OFFSET(zl
) =
490 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
))+nextdiff
);
493 /* Move tail to the front of the ziplist */
494 memmove(first
.p
,p
-nextdiff
,
495 intrev32ifbe(ZIPLIST_BYTES(zl
))-(p
-zl
)-1+nextdiff
);
497 /* The entire tail was deleted. No need to move memory. */
498 ZIPLIST_TAIL_OFFSET(zl
) =
499 intrev32ifbe((first
.p
-zl
)-first
.prevrawlen
);
502 /* Resize and update length */
504 zl
= ziplistResize(zl
, intrev32ifbe(ZIPLIST_BYTES(zl
))-totlen
+nextdiff
);
505 ZIPLIST_INCR_LENGTH(zl
,-deleted
);
508 /* When nextdiff != 0, the raw length of the next entry has changed, so
509 * we need to cascade the update throughout the ziplist */
511 zl
= __ziplistCascadeUpdate(zl
,p
);
516 /* Insert item at "p". */
517 static unsigned char *__ziplistInsert(unsigned char *zl
, unsigned char *p
, unsigned char *s
, unsigned int slen
) {
518 size_t curlen
= intrev32ifbe(ZIPLIST_BYTES(zl
)), reqlen
, prevlen
= 0;
521 unsigned char encoding
= 0;
522 long long value
= 123456789; /* initialized to avoid warning. Using a value
523 that is easy to see if for some reason
524 we use it uninitialized. */
527 /* Find out prevlen for the entry that is inserted. */
528 if (p
[0] != ZIP_END
) {
530 prevlen
= entry
.prevrawlen
;
532 unsigned char *ptail
= ZIPLIST_ENTRY_TAIL(zl
);
533 if (ptail
[0] != ZIP_END
) {
534 prevlen
= zipRawEntryLength(ptail
);
538 /* See if the entry can be encoded */
539 if (zipTryEncoding(s
,slen
,&value
,&encoding
)) {
540 /* 'encoding' is set to the appropriate integer encoding */
541 reqlen
= zipIntSize(encoding
);
543 /* 'encoding' is untouched, however zipEncodeLength will use the
544 * string length to figure out how to encode it. */
547 /* We need space for both the length of the previous entry and
548 * the length of the payload. */
549 reqlen
+= zipPrevEncodeLength(NULL
,prevlen
);
550 reqlen
+= zipEncodeLength(NULL
,encoding
,slen
);
552 /* When the insert position is not equal to the tail, we need to
553 * make sure that the next entry can hold this entry's length in
554 * its prevlen field. */
555 nextdiff
= (p
[0] != ZIP_END
) ? zipPrevLenByteDiff(p
,reqlen
) : 0;
557 /* Store offset because a realloc may change the address of zl. */
559 zl
= ziplistResize(zl
,curlen
+reqlen
+nextdiff
);
562 /* Apply memory move when necessary and update tail offset. */
563 if (p
[0] != ZIP_END
) {
564 /* Subtract one because of the ZIP_END bytes */
565 memmove(p
+reqlen
,p
-nextdiff
,curlen
-offset
-1+nextdiff
);
567 /* Encode this entry's raw length in the next entry. */
568 zipPrevEncodeLength(p
+reqlen
,reqlen
);
570 /* Update offset for tail */
571 ZIPLIST_TAIL_OFFSET(zl
) =
572 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
))+reqlen
);
574 /* When the tail contains more than one entry, we need to take
575 * "nextdiff" in account as well. Otherwise, a change in the
576 * size of prevlen doesn't have an effect on the *tail* offset. */
577 tail
= zipEntry(p
+reqlen
);
578 if (p
[reqlen
+tail
.headersize
+tail
.len
] != ZIP_END
) {
579 ZIPLIST_TAIL_OFFSET(zl
) =
580 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
))+nextdiff
);
583 /* This element will be the new tail. */
584 ZIPLIST_TAIL_OFFSET(zl
) = intrev32ifbe(p
-zl
);
587 /* When nextdiff != 0, the raw length of the next entry has changed, so
588 * we need to cascade the update throughout the ziplist */
591 zl
= __ziplistCascadeUpdate(zl
,p
+reqlen
);
595 /* Write the entry */
596 p
+= zipPrevEncodeLength(p
,prevlen
);
597 p
+= zipEncodeLength(p
,encoding
,slen
);
598 if (ZIP_IS_STR(encoding
)) {
601 zipSaveInteger(p
,value
,encoding
);
603 ZIPLIST_INCR_LENGTH(zl
,1);
607 unsigned char *ziplistPush(unsigned char *zl
, unsigned char *s
, unsigned int slen
, int where
) {
609 p
= (where
== ZIPLIST_HEAD
) ? ZIPLIST_ENTRY_HEAD(zl
) : ZIPLIST_ENTRY_END(zl
);
610 return __ziplistInsert(zl
,p
,s
,slen
);
613 /* Returns an offset to use for iterating with ziplistNext. When the given
614 * index is negative, the list is traversed back to front. When the list
615 * doesn't contain an element at the provided index, NULL is returned. */
616 unsigned char *ziplistIndex(unsigned char *zl
, int index
) {
621 p
= ZIPLIST_ENTRY_TAIL(zl
);
622 if (p
[0] != ZIP_END
) {
624 while (entry
.prevrawlen
> 0 && index
--) {
625 p
-= entry
.prevrawlen
;
630 p
= ZIPLIST_ENTRY_HEAD(zl
);
631 while (p
[0] != ZIP_END
&& index
--) {
632 p
+= zipRawEntryLength(p
);
635 return (p
[0] == ZIP_END
|| index
> 0) ? NULL
: p
;
638 /* Return pointer to next entry in ziplist.
640 * zl is the pointer to the ziplist
641 * p is the pointer to the current element
643 * The element after 'p' is returned, otherwise NULL if we are at the end. */
644 unsigned char *ziplistNext(unsigned char *zl
, unsigned char *p
) {
647 /* "p" could be equal to ZIP_END, caused by ziplistDelete,
648 * and we should return NULL. Otherwise, we should return NULL
649 * when the *next* element is ZIP_END (there is no next entry). */
650 if (p
[0] == ZIP_END
) {
654 p
+= zipRawEntryLength(p
);
655 if (p
[0] == ZIP_END
) {
662 /* Return pointer to previous entry in ziplist. */
663 unsigned char *ziplistPrev(unsigned char *zl
, unsigned char *p
) {
666 /* Iterating backwards from ZIP_END should return the tail. When "p" is
667 * equal to the first element of the list, we're already at the head,
668 * and should return NULL. */
669 if (p
[0] == ZIP_END
) {
670 p
= ZIPLIST_ENTRY_TAIL(zl
);
671 return (p
[0] == ZIP_END
) ? NULL
: p
;
672 } else if (p
== ZIPLIST_ENTRY_HEAD(zl
)) {
676 assert(entry
.prevrawlen
> 0);
677 return p
-entry
.prevrawlen
;
681 /* Get entry pointer to by 'p' and store in either 'e' or 'v' depending
682 * on the encoding of the entry. 'e' is always set to NULL to be able
683 * to find out whether the string pointer or the integer value was set.
684 * Return 0 if 'p' points to the end of the zipmap, 1 otherwise. */
685 unsigned int ziplistGet(unsigned char *p
, unsigned char **sstr
, unsigned int *slen
, long long *sval
) {
687 if (p
== NULL
|| p
[0] == ZIP_END
) return 0;
688 if (sstr
) *sstr
= NULL
;
691 if (ZIP_IS_STR(entry
.encoding
)) {
694 *sstr
= p
+entry
.headersize
;
698 *sval
= zipLoadInteger(p
+entry
.headersize
,entry
.encoding
);
704 /* Insert an entry at "p". */
705 unsigned char *ziplistInsert(unsigned char *zl
, unsigned char *p
, unsigned char *s
, unsigned int slen
) {
706 return __ziplistInsert(zl
,p
,s
,slen
);
709 /* Delete a single entry from the ziplist, pointed to by *p.
710 * Also update *p in place, to be able to iterate over the
711 * ziplist, while deleting entries. */
712 unsigned char *ziplistDelete(unsigned char *zl
, unsigned char **p
) {
713 size_t offset
= *p
-zl
;
714 zl
= __ziplistDelete(zl
,*p
,1);
716 /* Store pointer to current element in p, because ziplistDelete will
717 * do a realloc which might result in a different "zl"-pointer.
718 * When the delete direction is back to front, we might delete the last
719 * entry and end up with "p" pointing to ZIP_END, so check this. */
724 /* Delete a range of entries from the ziplist. */
725 unsigned char *ziplistDeleteRange(unsigned char *zl
, unsigned int index
, unsigned int num
) {
726 unsigned char *p
= ziplistIndex(zl
,index
);
727 return (p
== NULL
) ? zl
: __ziplistDelete(zl
,p
,num
);
730 /* Compare entry pointer to by 'p' with 'entry'. Return 1 if equal. */
731 unsigned int ziplistCompare(unsigned char *p
, unsigned char *sstr
, unsigned int slen
) {
733 unsigned char sencoding
;
734 long long zval
, sval
;
735 if (p
[0] == ZIP_END
) return 0;
738 if (ZIP_IS_STR(entry
.encoding
)) {
740 if (entry
.len
== slen
) {
741 return memcmp(p
+entry
.headersize
,sstr
,slen
) == 0;
746 /* Try to compare encoded values */
747 if (zipTryEncoding(sstr
,slen
,&sval
,&sencoding
)) {
748 if (entry
.encoding
== sencoding
) {
749 zval
= zipLoadInteger(p
+entry
.headersize
,entry
.encoding
);
757 /* Find pointer to the entry equal to the specified entry. Skip 'skip' entries
758 * between every comparison. Returns NULL when the field could not be found. */
759 unsigned char *ziplistFind(unsigned char *p
, unsigned char *vstr
, unsigned int vlen
, unsigned int skip
) {
761 unsigned char vencoding
= 0;
764 while (p
[0] != ZIP_END
) {
765 unsigned int prevlensize
, encoding
, lensize
, len
;
768 ZIP_DECODE_PREVLENSIZE(p
, prevlensize
);
769 ZIP_DECODE_LENGTH(p
+ prevlensize
, encoding
, lensize
, len
);
770 q
= p
+ prevlensize
+ lensize
;
773 /* Compare current entry with specified entry */
774 if (ZIP_IS_STR(encoding
)) {
775 if (len
== vlen
&& memcmp(q
, vstr
, vlen
) == 0) {
779 /* Find out if the specified entry can be encoded */
780 if (vencoding
== 0) {
781 /* UINT_MAX when the entry CANNOT be encoded */
782 if (!zipTryEncoding(vstr
, vlen
, &vll
, &vencoding
)) {
783 vencoding
= UCHAR_MAX
;
786 /* Must be non-zero by now */
790 /* Compare current entry with specified entry */
791 if (encoding
== vencoding
) {
792 long long ll
= zipLoadInteger(q
, encoding
);
799 /* Reset skip count */
806 /* Move to next entry */
813 /* Return length of ziplist. */
814 unsigned int ziplistLen(unsigned char *zl
) {
815 unsigned int len
= 0;
816 if (intrev16ifbe(ZIPLIST_LENGTH(zl
)) < UINT16_MAX
) {
817 len
= intrev16ifbe(ZIPLIST_LENGTH(zl
));
819 unsigned char *p
= zl
+ZIPLIST_HEADER_SIZE
;
820 while (*p
!= ZIP_END
) {
821 p
+= zipRawEntryLength(p
);
825 /* Re-store length if small enough */
826 if (len
< UINT16_MAX
) ZIPLIST_LENGTH(zl
) = intrev16ifbe(len
);
831 /* Return ziplist blob size in bytes. */
832 size_t ziplistBlobLen(unsigned char *zl
) {
833 return intrev32ifbe(ZIPLIST_BYTES(zl
));
836 void ziplistRepr(unsigned char *zl
) {
844 "{tail offset %u}\n",
845 intrev32ifbe(ZIPLIST_BYTES(zl
)),
846 intrev16ifbe(ZIPLIST_LENGTH(zl
)),
847 intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl
)));
848 p
= ZIPLIST_ENTRY_HEAD(zl
);
849 while(*p
!= ZIP_END
) {
864 (unsigned long) (p
-zl
),
865 entry
.headersize
+entry
.len
,
868 entry
.prevrawlensize
,
870 p
+= entry
.headersize
;
871 if (ZIP_IS_STR(entry
.encoding
)) {
872 if (entry
.len
> 40) {
873 if (fwrite(p
,40,1,stdout
) == 0) perror("fwrite");
877 fwrite(p
,entry
.len
,1,stdout
) == 0) perror("fwrite");
880 printf("%lld", (long long) zipLoadInteger(p
,entry
.encoding
));
889 #ifdef ZIPLIST_TEST_MAIN
890 #include <sys/time.h>
894 #define debug(f, ...) { if (DEBUG) printf(f, __VA_ARGS__); }
896 unsigned char *createList() {
897 unsigned char *zl
= ziplistNew();
898 zl
= ziplistPush(zl
, (unsigned char*)"foo", 3, ZIPLIST_TAIL
);
899 zl
= ziplistPush(zl
, (unsigned char*)"quux", 4, ZIPLIST_TAIL
);
900 zl
= ziplistPush(zl
, (unsigned char*)"hello", 5, ZIPLIST_HEAD
);
901 zl
= ziplistPush(zl
, (unsigned char*)"1024", 4, ZIPLIST_TAIL
);
905 unsigned char *createIntList() {
906 unsigned char *zl
= ziplistNew();
910 zl
= ziplistPush(zl
, (unsigned char*)buf
, strlen(buf
), ZIPLIST_TAIL
);
911 sprintf(buf
, "128000");
912 zl
= ziplistPush(zl
, (unsigned char*)buf
, strlen(buf
), ZIPLIST_TAIL
);
913 sprintf(buf
, "-100");
914 zl
= ziplistPush(zl
, (unsigned char*)buf
, strlen(buf
), ZIPLIST_HEAD
);
915 sprintf(buf
, "4294967296");
916 zl
= ziplistPush(zl
, (unsigned char*)buf
, strlen(buf
), ZIPLIST_HEAD
);
917 sprintf(buf
, "non integer");
918 zl
= ziplistPush(zl
, (unsigned char*)buf
, strlen(buf
), ZIPLIST_TAIL
);
919 sprintf(buf
, "much much longer non integer");
920 zl
= ziplistPush(zl
, (unsigned char*)buf
, strlen(buf
), ZIPLIST_TAIL
);
924 long long usec(void) {
926 gettimeofday(&tv
,NULL
);
927 return (((long long)tv
.tv_sec
)*1000000)+tv
.tv_usec
;
930 void stress(int pos
, int num
, int maxsize
, int dnum
) {
933 char posstr
[2][5] = { "HEAD", "TAIL" };
935 for (i
= 0; i
< maxsize
; i
+=dnum
) {
937 for (j
= 0; j
< i
; j
++) {
938 zl
= ziplistPush(zl
,(unsigned char*)"quux",4,ZIPLIST_TAIL
);
941 /* Do num times a push+pop from pos */
943 for (k
= 0; k
< num
; k
++) {
944 zl
= ziplistPush(zl
,(unsigned char*)"quux",4,pos
);
945 zl
= ziplistDeleteRange(zl
,0,1);
947 printf("List size: %8d, bytes: %8d, %dx push+pop (%s): %6lld usec\n",
948 i
,intrev32ifbe(ZIPLIST_BYTES(zl
)),num
,posstr
[pos
],usec()-start
);
953 void pop(unsigned char *zl
, int where
) {
954 unsigned char *p
, *vstr
;
958 p
= ziplistIndex(zl
,where
== ZIPLIST_HEAD
? 0 : -1);
959 if (ziplistGet(p
,&vstr
,&vlen
,&vlong
)) {
960 if (where
== ZIPLIST_HEAD
)
961 printf("Pop head: ");
963 printf("Pop tail: ");
966 if (vlen
&& fwrite(vstr
,vlen
,1,stdout
) == 0) perror("fwrite");
968 printf("%lld", vlong
);
971 ziplistDeleteRange(zl
,-1,1);
973 printf("ERROR: Could not pop\n");
978 int randstring(char *target
, unsigned int min
, unsigned int max
) {
979 int p
, len
= min
+rand()%(max
-min
+1);
999 target
[p
++] = minval
+rand()%(maxval
-minval
+1);
1003 int main(int argc
, char **argv
) {
1004 unsigned char *zl
, *p
;
1005 unsigned char *entry
;
1009 /* If an argument is given, use it as the random seed. */
1011 srand(atoi(argv
[1]));
1013 zl
= createIntList();
1019 pop(zl
,ZIPLIST_TAIL
);
1022 pop(zl
,ZIPLIST_HEAD
);
1025 pop(zl
,ZIPLIST_TAIL
);
1028 pop(zl
,ZIPLIST_TAIL
);
1031 printf("Get element at index 3:\n");
1034 p
= ziplistIndex(zl
, 3);
1035 if (!ziplistGet(p
, &entry
, &elen
, &value
)) {
1036 printf("ERROR: Could not access index 3\n");
1040 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1043 printf("%lld\n", value
);
1048 printf("Get element at index 4 (out of range):\n");
1051 p
= ziplistIndex(zl
, 4);
1053 printf("No entry\n");
1055 printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p
-zl
);
1061 printf("Get element at index -1 (last element):\n");
1064 p
= ziplistIndex(zl
, -1);
1065 if (!ziplistGet(p
, &entry
, &elen
, &value
)) {
1066 printf("ERROR: Could not access index -1\n");
1070 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1073 printf("%lld\n", value
);
1078 printf("Get element at index -4 (first element):\n");
1081 p
= ziplistIndex(zl
, -4);
1082 if (!ziplistGet(p
, &entry
, &elen
, &value
)) {
1083 printf("ERROR: Could not access index -4\n");
1087 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1090 printf("%lld\n", value
);
1095 printf("Get element at index -5 (reverse out of range):\n");
1098 p
= ziplistIndex(zl
, -5);
1100 printf("No entry\n");
1102 printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p
-zl
);
1108 printf("Iterate list from 0 to end:\n");
1111 p
= ziplistIndex(zl
, 0);
1112 while (ziplistGet(p
, &entry
, &elen
, &value
)) {
1115 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1117 printf("%lld", value
);
1119 p
= ziplistNext(zl
,p
);
1125 printf("Iterate list from 1 to end:\n");
1128 p
= ziplistIndex(zl
, 1);
1129 while (ziplistGet(p
, &entry
, &elen
, &value
)) {
1132 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1134 printf("%lld", value
);
1136 p
= ziplistNext(zl
,p
);
1142 printf("Iterate list from 2 to end:\n");
1145 p
= ziplistIndex(zl
, 2);
1146 while (ziplistGet(p
, &entry
, &elen
, &value
)) {
1149 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1151 printf("%lld", value
);
1153 p
= ziplistNext(zl
,p
);
1159 printf("Iterate starting out of range:\n");
1162 p
= ziplistIndex(zl
, 4);
1163 if (!ziplistGet(p
, &entry
, &elen
, &value
)) {
1164 printf("No entry\n");
1171 printf("Iterate from back to front:\n");
1174 p
= ziplistIndex(zl
, -1);
1175 while (ziplistGet(p
, &entry
, &elen
, &value
)) {
1178 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1180 printf("%lld", value
);
1182 p
= ziplistPrev(zl
,p
);
1188 printf("Iterate from back to front, deleting all items:\n");
1191 p
= ziplistIndex(zl
, -1);
1192 while (ziplistGet(p
, &entry
, &elen
, &value
)) {
1195 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0) perror("fwrite");
1197 printf("%lld", value
);
1199 zl
= ziplistDelete(zl
,&p
);
1200 p
= ziplistPrev(zl
,p
);
1206 printf("Delete inclusive range 0,0:\n");
1209 zl
= ziplistDeleteRange(zl
, 0, 1);
1213 printf("Delete inclusive range 0,1:\n");
1216 zl
= ziplistDeleteRange(zl
, 0, 2);
1220 printf("Delete inclusive range 1,2:\n");
1223 zl
= ziplistDeleteRange(zl
, 1, 2);
1227 printf("Delete with start index out of range:\n");
1230 zl
= ziplistDeleteRange(zl
, 5, 1);
1234 printf("Delete with num overflow:\n");
1237 zl
= ziplistDeleteRange(zl
, 1, 5);
1241 printf("Delete foo while iterating:\n");
1244 p
= ziplistIndex(zl
,0);
1245 while (ziplistGet(p
,&entry
,&elen
,&value
)) {
1246 if (entry
&& strncmp("foo",(char*)entry
,elen
) == 0) {
1247 printf("Delete foo\n");
1248 zl
= ziplistDelete(zl
,&p
);
1252 if (elen
&& fwrite(entry
,elen
,1,stdout
) == 0)
1255 printf("%lld",value
);
1257 p
= ziplistNext(zl
,p
);
1265 printf("Regression test for >255 byte strings:\n");
1267 char v1
[257],v2
[257];
1271 zl
= ziplistPush(zl
,(unsigned char*)v1
,strlen(v1
),ZIPLIST_TAIL
);
1272 zl
= ziplistPush(zl
,(unsigned char*)v2
,strlen(v2
),ZIPLIST_TAIL
);
1274 /* Pop values again and compare their value. */
1275 p
= ziplistIndex(zl
,0);
1276 assert(ziplistGet(p
,&entry
,&elen
,&value
));
1277 assert(strncmp(v1
,(char*)entry
,elen
) == 0);
1278 p
= ziplistIndex(zl
,1);
1279 assert(ziplistGet(p
,&entry
,&elen
,&value
));
1280 assert(strncmp(v2
,(char*)entry
,elen
) == 0);
1281 printf("SUCCESS\n\n");
1284 printf("Create long list and check indices:\n");
1289 for (i
= 0; i
< 1000; i
++) {
1290 len
= sprintf(buf
,"%d",i
);
1291 zl
= ziplistPush(zl
,(unsigned char*)buf
,len
,ZIPLIST_TAIL
);
1293 for (i
= 0; i
< 1000; i
++) {
1294 p
= ziplistIndex(zl
,i
);
1295 assert(ziplistGet(p
,NULL
,NULL
,&value
));
1298 p
= ziplistIndex(zl
,-i
-1);
1299 assert(ziplistGet(p
,NULL
,NULL
,&value
));
1300 assert(999-i
== value
);
1302 printf("SUCCESS\n\n");
1305 printf("Compare strings with ziplist entries:\n");
1308 p
= ziplistIndex(zl
,0);
1309 if (!ziplistCompare(p
,(unsigned char*)"hello",5)) {
1310 printf("ERROR: not \"hello\"\n");
1313 if (ziplistCompare(p
,(unsigned char*)"hella",5)) {
1314 printf("ERROR: \"hella\"\n");
1318 p
= ziplistIndex(zl
,3);
1319 if (!ziplistCompare(p
,(unsigned char*)"1024",4)) {
1320 printf("ERROR: not \"1024\"\n");
1323 if (ziplistCompare(p
,(unsigned char*)"1025",4)) {
1324 printf("ERROR: \"1025\"\n");
1327 printf("SUCCESS\n\n");
1330 printf("Stress with random payloads of different encoding:\n");
1339 /* Hold temp vars from ziplist */
1340 unsigned char *sstr
;
1344 for (i
= 0; i
< 20000; i
++) {
1347 listSetFreeMethod(ref
,sdsfree
);
1351 for (j
= 0; j
< len
; j
++) {
1352 where
= (rand() & 1) ? ZIPLIST_HEAD
: ZIPLIST_TAIL
;
1354 buflen
= randstring(buf
,1,sizeof(buf
)-1);
1356 switch(rand() % 3) {
1358 buflen
= sprintf(buf
,"%lld",(0LL + rand()) >> 20);
1361 buflen
= sprintf(buf
,"%lld",(0LL + rand()));
1364 buflen
= sprintf(buf
,"%lld",(0LL + rand()) << 20);
1371 /* Add to ziplist */
1372 zl
= ziplistPush(zl
, (unsigned char*)buf
, buflen
, where
);
1374 /* Add to reference list */
1375 if (where
== ZIPLIST_HEAD
) {
1376 listAddNodeHead(ref
,sdsnewlen(buf
, buflen
));
1377 } else if (where
== ZIPLIST_TAIL
) {
1378 listAddNodeTail(ref
,sdsnewlen(buf
, buflen
));
1384 assert(listLength(ref
) == ziplistLen(zl
));
1385 for (j
= 0; j
< len
; j
++) {
1386 /* Naive way to get elements, but similar to the stresser
1387 * executed from the Tcl test suite. */
1388 p
= ziplistIndex(zl
,j
);
1389 refnode
= listIndex(ref
,j
);
1391 assert(ziplistGet(p
,&sstr
,&slen
,&sval
));
1393 buflen
= sprintf(buf
,"%lld",sval
);
1396 memcpy(buf
,sstr
,buflen
);
1399 assert(memcmp(buf
,listNodeValue(refnode
),buflen
) == 0);
1404 printf("SUCCESS\n\n");
1407 printf("Stress with variable ziplist size:\n");
1409 stress(ZIPLIST_HEAD
,100000,16384,256);
1410 stress(ZIPLIST_TAIL
,100000,16384,256);