]> git.saurik.com Git - redis.git/blame_incremental - src/ziplist.c
ziplist.c: added comments about the new 24 bit encoding.
[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 * |1111____| - 1 byte
62 * Integer encoded as 24 bit signed (3 bytes).
63 *
64 * All the integers are represented in little endian byte order.
65 */
66
67#include <stdio.h>
68#include <stdlib.h>
69#include <string.h>
70#include <stdint.h>
71#include <assert.h>
72#include <limits.h>
73#include "zmalloc.h"
74#include "util.h"
75#include "ziplist.h"
76#include "endianconv.h"
77
78#define ZIP_END 255
79#define ZIP_BIGLEN 254
80
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)
91
92#define INT24_MAX 0x7fffff
93#define INT24_MIN (-INT24_MAX - 1)
94
95/* Macro to determine type */
96#define ZIP_IS_STR(enc) (((enc) & ZIP_STR_MASK) < ZIP_STR_MASK)
97
98/* Utility macros */
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)
106
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); \
112}
113
114typedef struct zlentry {
115 unsigned int prevrawlensize, prevrawlen;
116 unsigned int lensize, len;
117 unsigned int headersize;
118 unsigned char encoding;
119 unsigned char *p;
120} zlentry;
121
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; \
127 } \
128} while(0)
129
130/* Return bytes needed to store integer encoded by 'encoding' */
131static unsigned int zipIntSize(unsigned char encoding) {
132 switch(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);
137 }
138 assert(NULL);
139 return 0;
140}
141
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. */
144static unsigned int zipEncodeLength(unsigned char *p, unsigned char encoding, unsigned int rawlen) {
145 unsigned char len = 1, buf[5];
146
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) {
151 if (!p) return len;
152 buf[0] = ZIP_STR_06B | rawlen;
153 } else if (rawlen <= 0x3fff) {
154 len += 1;
155 if (!p) return len;
156 buf[0] = ZIP_STR_14B | ((rawlen >> 8) & 0x3f);
157 buf[1] = rawlen & 0xff;
158 } else {
159 len += 4;
160 if (!p) return len;
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;
166 }
167 } else {
168 /* Implies integer encoding, so length is always 1. */
169 if (!p) return len;
170 buf[0] = encoding;
171 }
172
173 /* Store this length at p */
174 memcpy(p,buf,len);
175 return len;
176}
177
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
181 * entries length. */
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) { \
186 (lensize) = 1; \
187 (len) = (ptr)[0] & 0x3f; \
188 } else if ((encoding) == ZIP_STR_14B) { \
189 (lensize) = 2; \
190 (len) = (((ptr)[0] & 0x3f) << 8) | (ptr)[1]; \
191 } else if (encoding == ZIP_STR_32B) { \
192 (lensize) = 5; \
193 (len) = ((ptr)[1] << 24) | \
194 ((ptr)[2] << 16) | \
195 ((ptr)[3] << 8) | \
196 ((ptr)[4]); \
197 } else { \
198 assert(NULL); \
199 } \
200 } else { \
201 (lensize) = 1; \
202 (len) = zipIntSize(encoding); \
203 } \
204} while(0);
205
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. */
208static unsigned int zipPrevEncodeLength(unsigned char *p, unsigned int len) {
209 if (p == NULL) {
210 return (len < ZIP_BIGLEN) ? 1 : sizeof(len)+1;
211 } else {
212 if (len < ZIP_BIGLEN) {
213 p[0] = len;
214 return 1;
215 } else {
216 p[0] = ZIP_BIGLEN;
217 memcpy(p+1,&len,sizeof(len));
218 memrev32ifbe(p+1);
219 return 1+sizeof(len);
220 }
221 }
222}
223
224/* Encode the length of the previous entry and write it to "p". This only
225 * uses the larger encoding (required in __ziplistCascadeUpdate). */
226static void zipPrevEncodeLengthForceLarge(unsigned char *p, unsigned int len) {
227 if (p == NULL) return;
228 p[0] = ZIP_BIGLEN;
229 memcpy(p+1,&len,sizeof(len));
230 memrev32ifbe(p+1);
231}
232
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) { \
237 (prevlensize) = 1; \
238 } else { \
239 (prevlensize) = 5; \
240 } \
241} while(0);
242
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); \
253 } \
254} while(0);
255
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'. */
258static int zipPrevLenByteDiff(unsigned char *p, unsigned int len) {
259 unsigned int prevlensize;
260 ZIP_DECODE_PREVLENSIZE(p, prevlensize);
261 return zipPrevEncodeLength(NULL, len) - prevlensize;
262}
263
264/* Return the total number of bytes used by the entry pointed to by 'p'. */
265static 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;
270}
271
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'. */
274static int zipTryEncoding(unsigned char *entry, unsigned int entrylen, long long *v, unsigned char *encoding) {
275 long long value;
276
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;
287 } else {
288 *encoding = ZIP_INT_64B;
289 }
290 *v = value;
291 return 1;
292 }
293 return 0;
294}
295
296/* Store integer 'value' at 'p', encoded as 'encoding' */
297static void zipSaveInteger(unsigned char *p, int64_t value, unsigned char encoding) {
298 int16_t i16;
299 int32_t i32;
300 int64_t i64;
301 if (encoding == ZIP_INT_16B) {
302 i16 = value;
303 memcpy(p,&i16,sizeof(i16));
304 memrev16ifbe(p);
305 } else if (encoding == ZIP_INT_24B) {
306 i32 = value<<8;
307 memrev32ifbe(&i32);
308 memcpy(p,((unsigned char*)&i32)+1,sizeof(i32)-sizeof(int8_t));
309 } else if (encoding == ZIP_INT_32B) {
310 i32 = value;
311 memcpy(p,&i32,sizeof(i32));
312 memrev32ifbe(p);
313 } else if (encoding == ZIP_INT_64B) {
314 i64 = value;
315 memcpy(p,&i64,sizeof(i64));
316 memrev64ifbe(p);
317 } else {
318 assert(NULL);
319 }
320}
321
322/* Read integer encoded as 'encoding' from 'p' */
323static int64_t zipLoadInteger(unsigned char *p, unsigned char encoding) {
324 int16_t i16;
325 int32_t i32;
326 int64_t i64, ret = 0;
327 if (encoding == ZIP_INT_16B) {
328 memcpy(&i16,p,sizeof(i16));
329 memrev16ifbe(&i16);
330 ret = i16;
331 } else if (encoding == ZIP_INT_32B) {
332 memcpy(&i32,p,sizeof(i32));
333 memrev32ifbe(&i32);
334 ret = i32;
335 } else if (encoding == ZIP_INT_24B) {
336 i32 = 0;
337 memcpy(((unsigned char*)&i32)+1,p,sizeof(i32)-sizeof(int8_t));
338 memrev32ifbe(&i32);
339 ret = i32>>8;
340 } else if (encoding == ZIP_INT_64B) {
341 memcpy(&i64,p,sizeof(i64));
342 memrev64ifbe(&i64);
343 ret = i64;
344 } else {
345 assert(NULL);
346 }
347 return ret;
348}
349
350/* Return a struct with all information about an entry. */
351static zlentry zipEntry(unsigned char *p) {
352 zlentry e;
353
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;
357 e.p = p;
358 return e;
359}
360
361/* Create a new empty ziplist. */
362unsigned 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;
369 return zl;
370}
371
372/* Resize the ziplist. */
373static unsigned char *ziplistResize(unsigned char *zl, unsigned int len) {
374 zl = zrealloc(zl,len);
375 ZIPLIST_BYTES(zl) = intrev32ifbe(len);
376 zl[len-1] = ZIP_END;
377 return zl;
378}
379
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
389 * consecutive entry.
390 *
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.
397 *
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. */
400static 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;
403 unsigned char *np;
404 zlentry cur, next;
405
406 while (p[0] != ZIP_END) {
407 cur = zipEntry(p);
408 rawlen = cur.headersize + cur.len;
409 rawlensize = zipPrevEncodeLength(NULL,rawlen);
410
411 /* Abort if there is no next entry. */
412 if (p[rawlen] == ZIP_END) break;
413 next = zipEntry(p+rawlen);
414
415 /* Abort when "prevlen" has not changed. */
416 if (next.prevrawlen == rawlen) break;
417
418 if (next.prevrawlensize < rawlensize) {
419 /* The "prevlen" field of "next" needs more bytes to hold
420 * the raw length of "cur". */
421 offset = p-zl;
422 extra = rawlensize-next.prevrawlensize;
423 zl = ziplistResize(zl,curlen+extra);
424 p = zl+offset;
425
426 /* Current pointer and offset for next element. */
427 np = p+rawlen;
428 noffset = np-zl;
429
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);
434 }
435
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);
441
442 /* Advance the cursor */
443 p += rawlen;
444 curlen += extra;
445 } else {
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);
450 } else {
451 zipPrevEncodeLength(p+rawlen,rawlen);
452 }
453
454 /* Stop here, as the raw length of "next" has not changed. */
455 break;
456 }
457 }
458 return zl;
459}
460
461/* Delete "num" entries, starting at "p". Returns pointer to the ziplist. */
462static unsigned char *__ziplistDelete(unsigned char *zl, unsigned char *p, unsigned int num) {
463 unsigned int i, totlen, deleted = 0;
464 size_t offset;
465 int nextdiff = 0;
466 zlentry first, tail;
467
468 first = zipEntry(p);
469 for (i = 0; p[0] != ZIP_END && i < num; i++) {
470 p += zipRawEntryLength(p);
471 deleted++;
472 }
473
474 totlen = p-first.p;
475 if (totlen > 0) {
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);
483
484 /* Update offset for tail */
485 ZIPLIST_TAIL_OFFSET(zl) =
486 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))-totlen);
487
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. */
491 tail = zipEntry(p);
492 if (p[tail.headersize+tail.len] != ZIP_END) {
493 ZIPLIST_TAIL_OFFSET(zl) =
494 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+nextdiff);
495 }
496
497 /* Move tail to the front of the ziplist */
498 memmove(first.p,p-nextdiff,
499 intrev32ifbe(ZIPLIST_BYTES(zl))-(p-zl)-1+nextdiff);
500 } else {
501 /* The entire tail was deleted. No need to move memory. */
502 ZIPLIST_TAIL_OFFSET(zl) =
503 intrev32ifbe((first.p-zl)-first.prevrawlen);
504 }
505
506 /* Resize and update length */
507 offset = first.p-zl;
508 zl = ziplistResize(zl, intrev32ifbe(ZIPLIST_BYTES(zl))-totlen+nextdiff);
509 ZIPLIST_INCR_LENGTH(zl,-deleted);
510 p = zl+offset;
511
512 /* When nextdiff != 0, the raw length of the next entry has changed, so
513 * we need to cascade the update throughout the ziplist */
514 if (nextdiff != 0)
515 zl = __ziplistCascadeUpdate(zl,p);
516 }
517 return zl;
518}
519
520/* Insert item at "p". */
521static 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;
523 size_t offset;
524 int nextdiff = 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. */
529 zlentry entry, tail;
530
531 /* Find out prevlen for the entry that is inserted. */
532 if (p[0] != ZIP_END) {
533 entry = zipEntry(p);
534 prevlen = entry.prevrawlen;
535 } else {
536 unsigned char *ptail = ZIPLIST_ENTRY_TAIL(zl);
537 if (ptail[0] != ZIP_END) {
538 prevlen = zipRawEntryLength(ptail);
539 }
540 }
541
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);
546 } else {
547 /* 'encoding' is untouched, however zipEncodeLength will use the
548 * string length to figure out how to encode it. */
549 reqlen = slen;
550 }
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);
555
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;
560
561 /* Store offset because a realloc may change the address of zl. */
562 offset = p-zl;
563 zl = ziplistResize(zl,curlen+reqlen+nextdiff);
564 p = zl+offset;
565
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);
570
571 /* Encode this entry's raw length in the next entry. */
572 zipPrevEncodeLength(p+reqlen,reqlen);
573
574 /* Update offset for tail */
575 ZIPLIST_TAIL_OFFSET(zl) =
576 intrev32ifbe(intrev32ifbe(ZIPLIST_TAIL_OFFSET(zl))+reqlen);
577
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);
585 }
586 } else {
587 /* This element will be the new tail. */
588 ZIPLIST_TAIL_OFFSET(zl) = intrev32ifbe(p-zl);
589 }
590
591 /* When nextdiff != 0, the raw length of the next entry has changed, so
592 * we need to cascade the update throughout the ziplist */
593 if (nextdiff != 0) {
594 offset = p-zl;
595 zl = __ziplistCascadeUpdate(zl,p+reqlen);
596 p = zl+offset;
597 }
598
599 /* Write the entry */
600 p += zipPrevEncodeLength(p,prevlen);
601 p += zipEncodeLength(p,encoding,slen);
602 if (ZIP_IS_STR(encoding)) {
603 memcpy(p,s,slen);
604 } else {
605 zipSaveInteger(p,value,encoding);
606 }
607 ZIPLIST_INCR_LENGTH(zl,1);
608 return zl;
609}
610
611unsigned char *ziplistPush(unsigned char *zl, unsigned char *s, unsigned int slen, int where) {
612 unsigned char *p;
613 p = (where == ZIPLIST_HEAD) ? ZIPLIST_ENTRY_HEAD(zl) : ZIPLIST_ENTRY_END(zl);
614 return __ziplistInsert(zl,p,s,slen);
615}
616
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. */
620unsigned char *ziplistIndex(unsigned char *zl, int index) {
621 unsigned char *p;
622 zlentry entry;
623 if (index < 0) {
624 index = (-index)-1;
625 p = ZIPLIST_ENTRY_TAIL(zl);
626 if (p[0] != ZIP_END) {
627 entry = zipEntry(p);
628 while (entry.prevrawlen > 0 && index--) {
629 p -= entry.prevrawlen;
630 entry = zipEntry(p);
631 }
632 }
633 } else {
634 p = ZIPLIST_ENTRY_HEAD(zl);
635 while (p[0] != ZIP_END && index--) {
636 p += zipRawEntryLength(p);
637 }
638 }
639 return (p[0] == ZIP_END || index > 0) ? NULL : p;
640}
641
642/* Return pointer to next entry in ziplist.
643 *
644 * zl is the pointer to the ziplist
645 * p is the pointer to the current element
646 *
647 * The element after 'p' is returned, otherwise NULL if we are at the end. */
648unsigned char *ziplistNext(unsigned char *zl, unsigned char *p) {
649 ((void) zl);
650
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) {
655 return NULL;
656 }
657
658 p += zipRawEntryLength(p);
659 if (p[0] == ZIP_END) {
660 return NULL;
661 }
662
663 return p;
664}
665
666/* Return pointer to previous entry in ziplist. */
667unsigned char *ziplistPrev(unsigned char *zl, unsigned char *p) {
668 zlentry entry;
669
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)) {
677 return NULL;
678 } else {
679 entry = zipEntry(p);
680 assert(entry.prevrawlen > 0);
681 return p-entry.prevrawlen;
682 }
683}
684
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. */
689unsigned int ziplistGet(unsigned char *p, unsigned char **sstr, unsigned int *slen, long long *sval) {
690 zlentry entry;
691 if (p == NULL || p[0] == ZIP_END) return 0;
692 if (sstr) *sstr = NULL;
693
694 entry = zipEntry(p);
695 if (ZIP_IS_STR(entry.encoding)) {
696 if (sstr) {
697 *slen = entry.len;
698 *sstr = p+entry.headersize;
699 }
700 } else {
701 if (sval) {
702 *sval = zipLoadInteger(p+entry.headersize,entry.encoding);
703 }
704 }
705 return 1;
706}
707
708/* Insert an entry at "p". */
709unsigned char *ziplistInsert(unsigned char *zl, unsigned char *p, unsigned char *s, unsigned int slen) {
710 return __ziplistInsert(zl,p,s,slen);
711}
712
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. */
716unsigned char *ziplistDelete(unsigned char *zl, unsigned char **p) {
717 size_t offset = *p-zl;
718 zl = __ziplistDelete(zl,*p,1);
719
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. */
724 *p = zl+offset;
725 return zl;
726}
727
728/* Delete a range of entries from the ziplist. */
729unsigned 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);
732}
733
734/* Compare entry pointer to by 'p' with 'entry'. Return 1 if equal. */
735unsigned int ziplistCompare(unsigned char *p, unsigned char *sstr, unsigned int slen) {
736 zlentry entry;
737 unsigned char sencoding;
738 long long zval, sval;
739 if (p[0] == ZIP_END) return 0;
740
741 entry = zipEntry(p);
742 if (ZIP_IS_STR(entry.encoding)) {
743 /* Raw compare */
744 if (entry.len == slen) {
745 return memcmp(p+entry.headersize,sstr,slen) == 0;
746 } else {
747 return 0;
748 }
749 } else {
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);
754 return zval == sval;
755 }
756 }
757 }
758 return 0;
759}
760
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. */
763unsigned char *ziplistFind(unsigned char *p, unsigned char *vstr, unsigned int vlen, unsigned int skip) {
764 int skipcnt = 0;
765 unsigned char vencoding = 0;
766 long long vll = 0;
767
768 while (p[0] != ZIP_END) {
769 unsigned int prevlensize, encoding, lensize, len;
770 unsigned char *q;
771
772 ZIP_DECODE_PREVLENSIZE(p, prevlensize);
773 ZIP_DECODE_LENGTH(p + prevlensize, encoding, lensize, len);
774 q = p + prevlensize + lensize;
775
776 if (skipcnt == 0) {
777 /* Compare current entry with specified entry */
778 if (ZIP_IS_STR(encoding)) {
779 if (len == vlen && memcmp(q, vstr, vlen) == 0) {
780 return p;
781 }
782 } else {
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;
788 }
789
790 /* Must be non-zero by now */
791 assert(vencoding);
792 }
793
794 /* Compare current entry with specified entry */
795 if (encoding == vencoding) {
796 long long ll = zipLoadInteger(q, encoding);
797 if (ll == vll) {
798 return p;
799 }
800 }
801 }
802
803 /* Reset skip count */
804 skipcnt = skip;
805 } else {
806 /* Skip entry */
807 skipcnt--;
808 }
809
810 /* Move to next entry */
811 p = q + len;
812 }
813
814 return NULL;
815}
816
817/* Return length of ziplist. */
818unsigned int ziplistLen(unsigned char *zl) {
819 unsigned int len = 0;
820 if (intrev16ifbe(ZIPLIST_LENGTH(zl)) < UINT16_MAX) {
821 len = intrev16ifbe(ZIPLIST_LENGTH(zl));
822 } else {
823 unsigned char *p = zl+ZIPLIST_HEADER_SIZE;
824 while (*p != ZIP_END) {
825 p += zipRawEntryLength(p);
826 len++;
827 }
828
829 /* Re-store length if small enough */
830 if (len < UINT16_MAX) ZIPLIST_LENGTH(zl) = intrev16ifbe(len);
831 }
832 return len;
833}
834
835/* Return ziplist blob size in bytes. */
836size_t ziplistBlobLen(unsigned char *zl) {
837 return intrev32ifbe(ZIPLIST_BYTES(zl));
838}
839
840void ziplistRepr(unsigned char *zl) {
841 unsigned char *p;
842 int index = 0;
843 zlentry entry;
844
845 printf(
846 "{total bytes %d} "
847 "{length %u}\n"
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) {
854 entry = zipEntry(p);
855 printf(
856 "{"
857 "addr 0x%08lx, "
858 "index %2d, "
859 "offset %5ld, "
860 "rl: %5u, "
861 "hs %2u, "
862 "pl: %5u, "
863 "pls: %2u, "
864 "payload %5u"
865 "} ",
866 (long unsigned)p,
867 index,
868 (unsigned long) (p-zl),
869 entry.headersize+entry.len,
870 entry.headersize,
871 entry.prevrawlen,
872 entry.prevrawlensize,
873 entry.len);
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");
878 printf("...");
879 } else {
880 if (entry.len &&
881 fwrite(p,entry.len,1,stdout) == 0) perror("fwrite");
882 }
883 } else {
884 printf("%lld", (long long) zipLoadInteger(p,entry.encoding));
885 }
886 printf("\n");
887 p += entry.len;
888 index++;
889 }
890 printf("{end}\n\n");
891}
892
893#ifdef ZIPLIST_TEST_MAIN
894#include <sys/time.h>
895#include "adlist.h"
896#include "sds.h"
897
898#define debug(f, ...) { if (DEBUG) printf(f, __VA_ARGS__); }
899
900unsigned 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);
906 return zl;
907}
908
909unsigned char *createIntList() {
910 unsigned char *zl = ziplistNew();
911 char buf[32];
912
913 sprintf(buf, "100");
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);
925 return zl;
926}
927
928long long usec(void) {
929 struct timeval tv;
930 gettimeofday(&tv,NULL);
931 return (((long long)tv.tv_sec)*1000000)+tv.tv_usec;
932}
933
934void stress(int pos, int num, int maxsize, int dnum) {
935 int i,j,k;
936 unsigned char *zl;
937 char posstr[2][5] = { "HEAD", "TAIL" };
938 long long start;
939 for (i = 0; i < maxsize; i+=dnum) {
940 zl = ziplistNew();
941 for (j = 0; j < i; j++) {
942 zl = ziplistPush(zl,(unsigned char*)"quux",4,ZIPLIST_TAIL);
943 }
944
945 /* Do num times a push+pop from pos */
946 start = usec();
947 for (k = 0; k < num; k++) {
948 zl = ziplistPush(zl,(unsigned char*)"quux",4,pos);
949 zl = ziplistDeleteRange(zl,0,1);
950 }
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);
953 zfree(zl);
954 }
955}
956
957void pop(unsigned char *zl, int where) {
958 unsigned char *p, *vstr;
959 unsigned int vlen;
960 long long vlong;
961
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: ");
966 else
967 printf("Pop tail: ");
968
969 if (vstr)
970 if (vlen && fwrite(vstr,vlen,1,stdout) == 0) perror("fwrite");
971 else
972 printf("%lld", vlong);
973
974 printf("\n");
975 ziplistDeleteRange(zl,-1,1);
976 } else {
977 printf("ERROR: Could not pop\n");
978 exit(1);
979 }
980}
981
982int randstring(char *target, unsigned int min, unsigned int max) {
983 int p, len = min+rand()%(max-min+1);
984 int minval, maxval;
985 switch(rand() % 3) {
986 case 0:
987 minval = 0;
988 maxval = 255;
989 break;
990 case 1:
991 minval = 48;
992 maxval = 122;
993 break;
994 case 2:
995 minval = 48;
996 maxval = 52;
997 break;
998 default:
999 assert(NULL);
1000 }
1001
1002 while(p < len)
1003 target[p++] = minval+rand()%(maxval-minval+1);
1004 return len;
1005}
1006
1007int main(int argc, char **argv) {
1008 unsigned char *zl, *p;
1009 unsigned char *entry;
1010 unsigned int elen;
1011 long long value;
1012
1013 /* If an argument is given, use it as the random seed. */
1014 if (argc == 2)
1015 srand(atoi(argv[1]));
1016
1017 zl = createIntList();
1018 ziplistRepr(zl);
1019
1020 zl = createList();
1021 ziplistRepr(zl);
1022
1023 pop(zl,ZIPLIST_TAIL);
1024 ziplistRepr(zl);
1025
1026 pop(zl,ZIPLIST_HEAD);
1027 ziplistRepr(zl);
1028
1029 pop(zl,ZIPLIST_TAIL);
1030 ziplistRepr(zl);
1031
1032 pop(zl,ZIPLIST_TAIL);
1033 ziplistRepr(zl);
1034
1035 printf("Get element at index 3:\n");
1036 {
1037 zl = createList();
1038 p = ziplistIndex(zl, 3);
1039 if (!ziplistGet(p, &entry, &elen, &value)) {
1040 printf("ERROR: Could not access index 3\n");
1041 return 1;
1042 }
1043 if (entry) {
1044 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
1045 printf("\n");
1046 } else {
1047 printf("%lld\n", value);
1048 }
1049 printf("\n");
1050 }
1051
1052 printf("Get element at index 4 (out of range):\n");
1053 {
1054 zl = createList();
1055 p = ziplistIndex(zl, 4);
1056 if (p == NULL) {
1057 printf("No entry\n");
1058 } else {
1059 printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p-zl);
1060 return 1;
1061 }
1062 printf("\n");
1063 }
1064
1065 printf("Get element at index -1 (last element):\n");
1066 {
1067 zl = createList();
1068 p = ziplistIndex(zl, -1);
1069 if (!ziplistGet(p, &entry, &elen, &value)) {
1070 printf("ERROR: Could not access index -1\n");
1071 return 1;
1072 }
1073 if (entry) {
1074 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
1075 printf("\n");
1076 } else {
1077 printf("%lld\n", value);
1078 }
1079 printf("\n");
1080 }
1081
1082 printf("Get element at index -4 (first element):\n");
1083 {
1084 zl = createList();
1085 p = ziplistIndex(zl, -4);
1086 if (!ziplistGet(p, &entry, &elen, &value)) {
1087 printf("ERROR: Could not access index -4\n");
1088 return 1;
1089 }
1090 if (entry) {
1091 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
1092 printf("\n");
1093 } else {
1094 printf("%lld\n", value);
1095 }
1096 printf("\n");
1097 }
1098
1099 printf("Get element at index -5 (reverse out of range):\n");
1100 {
1101 zl = createList();
1102 p = ziplistIndex(zl, -5);
1103 if (p == NULL) {
1104 printf("No entry\n");
1105 } else {
1106 printf("ERROR: Out of range index should return NULL, returned offset: %ld\n", p-zl);
1107 return 1;
1108 }
1109 printf("\n");
1110 }
1111
1112 printf("Iterate list from 0 to end:\n");
1113 {
1114 zl = createList();
1115 p = ziplistIndex(zl, 0);
1116 while (ziplistGet(p, &entry, &elen, &value)) {
1117 printf("Entry: ");
1118 if (entry) {
1119 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
1120 } else {
1121 printf("%lld", value);
1122 }
1123 p = ziplistNext(zl,p);
1124 printf("\n");
1125 }
1126 printf("\n");
1127 }
1128
1129 printf("Iterate list from 1 to end:\n");
1130 {
1131 zl = createList();
1132 p = ziplistIndex(zl, 1);
1133 while (ziplistGet(p, &entry, &elen, &value)) {
1134 printf("Entry: ");
1135 if (entry) {
1136 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
1137 } else {
1138 printf("%lld", value);
1139 }
1140 p = ziplistNext(zl,p);
1141 printf("\n");
1142 }
1143 printf("\n");
1144 }
1145
1146 printf("Iterate list from 2 to end:\n");
1147 {
1148 zl = createList();
1149 p = ziplistIndex(zl, 2);
1150 while (ziplistGet(p, &entry, &elen, &value)) {
1151 printf("Entry: ");
1152 if (entry) {
1153 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
1154 } else {
1155 printf("%lld", value);
1156 }
1157 p = ziplistNext(zl,p);
1158 printf("\n");
1159 }
1160 printf("\n");
1161 }
1162
1163 printf("Iterate starting out of range:\n");
1164 {
1165 zl = createList();
1166 p = ziplistIndex(zl, 4);
1167 if (!ziplistGet(p, &entry, &elen, &value)) {
1168 printf("No entry\n");
1169 } else {
1170 printf("ERROR\n");
1171 }
1172 printf("\n");
1173 }
1174
1175 printf("Iterate from back to front:\n");
1176 {
1177 zl = createList();
1178 p = ziplistIndex(zl, -1);
1179 while (ziplistGet(p, &entry, &elen, &value)) {
1180 printf("Entry: ");
1181 if (entry) {
1182 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
1183 } else {
1184 printf("%lld", value);
1185 }
1186 p = ziplistPrev(zl,p);
1187 printf("\n");
1188 }
1189 printf("\n");
1190 }
1191
1192 printf("Iterate from back to front, deleting all items:\n");
1193 {
1194 zl = createList();
1195 p = ziplistIndex(zl, -1);
1196 while (ziplistGet(p, &entry, &elen, &value)) {
1197 printf("Entry: ");
1198 if (entry) {
1199 if (elen && fwrite(entry,elen,1,stdout) == 0) perror("fwrite");
1200 } else {
1201 printf("%lld", value);
1202 }
1203 zl = ziplistDelete(zl,&p);
1204 p = ziplistPrev(zl,p);
1205 printf("\n");
1206 }
1207 printf("\n");
1208 }
1209
1210 printf("Delete inclusive range 0,0:\n");
1211 {
1212 zl = createList();
1213 zl = ziplistDeleteRange(zl, 0, 1);
1214 ziplistRepr(zl);
1215 }
1216
1217 printf("Delete inclusive range 0,1:\n");
1218 {
1219 zl = createList();
1220 zl = ziplistDeleteRange(zl, 0, 2);
1221 ziplistRepr(zl);
1222 }
1223
1224 printf("Delete inclusive range 1,2:\n");
1225 {
1226 zl = createList();
1227 zl = ziplistDeleteRange(zl, 1, 2);
1228 ziplistRepr(zl);
1229 }
1230
1231 printf("Delete with start index out of range:\n");
1232 {
1233 zl = createList();
1234 zl = ziplistDeleteRange(zl, 5, 1);
1235 ziplistRepr(zl);
1236 }
1237
1238 printf("Delete with num overflow:\n");
1239 {
1240 zl = createList();
1241 zl = ziplistDeleteRange(zl, 1, 5);
1242 ziplistRepr(zl);
1243 }
1244
1245 printf("Delete foo while iterating:\n");
1246 {
1247 zl = createList();
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);
1253 } else {
1254 printf("Entry: ");
1255 if (entry) {
1256 if (elen && fwrite(entry,elen,1,stdout) == 0)
1257 perror("fwrite");
1258 } else {
1259 printf("%lld",value);
1260 }
1261 p = ziplistNext(zl,p);
1262 printf("\n");
1263 }
1264 }
1265 printf("\n");
1266 ziplistRepr(zl);
1267 }
1268
1269 printf("Regression test for >255 byte strings:\n");
1270 {
1271 char v1[257],v2[257];
1272 memset(v1,'x',256);
1273 memset(v2,'y',256);
1274 zl = ziplistNew();
1275 zl = ziplistPush(zl,(unsigned char*)v1,strlen(v1),ZIPLIST_TAIL);
1276 zl = ziplistPush(zl,(unsigned char*)v2,strlen(v2),ZIPLIST_TAIL);
1277
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");
1286 }
1287
1288 printf("Create long list and check indices:\n");
1289 {
1290 zl = ziplistNew();
1291 char buf[32];
1292 int i,len;
1293 for (i = 0; i < 1000; i++) {
1294 len = sprintf(buf,"%d",i);
1295 zl = ziplistPush(zl,(unsigned char*)buf,len,ZIPLIST_TAIL);
1296 }
1297 for (i = 0; i < 1000; i++) {
1298 p = ziplistIndex(zl,i);
1299 assert(ziplistGet(p,NULL,NULL,&value));
1300 assert(i == value);
1301
1302 p = ziplistIndex(zl,-i-1);
1303 assert(ziplistGet(p,NULL,NULL,&value));
1304 assert(999-i == value);
1305 }
1306 printf("SUCCESS\n\n");
1307 }
1308
1309 printf("Compare strings with ziplist entries:\n");
1310 {
1311 zl = createList();
1312 p = ziplistIndex(zl,0);
1313 if (!ziplistCompare(p,(unsigned char*)"hello",5)) {
1314 printf("ERROR: not \"hello\"\n");
1315 return 1;
1316 }
1317 if (ziplistCompare(p,(unsigned char*)"hella",5)) {
1318 printf("ERROR: \"hella\"\n");
1319 return 1;
1320 }
1321
1322 p = ziplistIndex(zl,3);
1323 if (!ziplistCompare(p,(unsigned char*)"1024",4)) {
1324 printf("ERROR: not \"1024\"\n");
1325 return 1;
1326 }
1327 if (ziplistCompare(p,(unsigned char*)"1025",4)) {
1328 printf("ERROR: \"1025\"\n");
1329 return 1;
1330 }
1331 printf("SUCCESS\n\n");
1332 }
1333
1334 printf("Stress with random payloads of different encoding:\n");
1335 {
1336 int i,j,len,where;
1337 unsigned char *p;
1338 char buf[1024];
1339 int buflen;
1340 list *ref;
1341 listNode *refnode;
1342
1343 /* Hold temp vars from ziplist */
1344 unsigned char *sstr;
1345 unsigned int slen;
1346 long long sval;
1347
1348 for (i = 0; i < 20000; i++) {
1349 zl = ziplistNew();
1350 ref = listCreate();
1351 listSetFreeMethod(ref,sdsfree);
1352 len = rand() % 256;
1353
1354 /* Create lists */
1355 for (j = 0; j < len; j++) {
1356 where = (rand() & 1) ? ZIPLIST_HEAD : ZIPLIST_TAIL;
1357 if (rand() % 2) {
1358 buflen = randstring(buf,1,sizeof(buf)-1);
1359 } else {
1360 switch(rand() % 3) {
1361 case 0:
1362 buflen = sprintf(buf,"%lld",(0LL + rand()) >> 20);
1363 break;
1364 case 1:
1365 buflen = sprintf(buf,"%lld",(0LL + rand()));
1366 break;
1367 case 2:
1368 buflen = sprintf(buf,"%lld",(0LL + rand()) << 20);
1369 break;
1370 default:
1371 assert(NULL);
1372 }
1373 }
1374
1375 /* Add to ziplist */
1376 zl = ziplistPush(zl, (unsigned char*)buf, buflen, where);
1377
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));
1383 } else {
1384 assert(NULL);
1385 }
1386 }
1387
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);
1394
1395 assert(ziplistGet(p,&sstr,&slen,&sval));
1396 if (sstr == NULL) {
1397 buflen = sprintf(buf,"%lld",sval);
1398 } else {
1399 buflen = slen;
1400 memcpy(buf,sstr,buflen);
1401 buf[buflen] = '\0';
1402 }
1403 assert(memcmp(buf,listNodeValue(refnode),buflen) == 0);
1404 }
1405 zfree(zl);
1406 listRelease(ref);
1407 }
1408 printf("SUCCESS\n\n");
1409 }
1410
1411 printf("Stress with variable ziplist size:\n");
1412 {
1413 stress(ZIPLIST_HEAD,100000,16384,256);
1414 stress(ZIPLIST_TAIL,100000,16384,256);
1415 }
1416
1417 return 0;
1418}
1419
1420#endif